Tutorial :Is Int32^ i = gcnew Int32() allocated on managed heap?



Question:

Basically I would like to know the difference between
Int32^ i = gcnew Int32();
and
Int32* i2 = new Int32();

I have written the following code:

#include <stdio.h>  #using <mscorlib.dll>    using namespace System;    int main(void) {        Int32^ i = gcnew Int32();      Int32* i2 = new Int32();        printf("%p %d\n", i2, *i2);      printf("%p %d\n", i, *i);        return 0;  }  

It gives the following output:

004158B8 0  00E1002C 0  

It seems the two integer are allocated in two different memory locations.

Is the gcnew Int32() allocated in managed heap? or directly on the stack?


Solution:1

In managed C++ new allocates on unmanaged heap, gcnew - on managed heap. Objects in the managed heap are eligible for garbage collection, while objects in the unmanaged heap are not. Pointers with ^ work like C# references - the runtime tracks them and uses for garbage collection, pointers with * work like normal C++ pointers.


Solution:2

I have got the answer. gcnew will allocate the object on managed heap, even the type is a value type.

Therefore, Int32^ i = gcnew Int32() will allocate the newly created object on managed heap.

The following code can prove this:

#include <stdio.h>  #using <mscorlib.dll>    using namespace System;    int main(void) {      Object^ o = gcnew Object();      long j = 0;        while (GC::GetGeneration(o) == 0) {          Int32^ i = gcnew Int32();          j += 4;            if (j % 100 == 0) {              printf("%d\n", i);          }      }        printf("Generation 0 collection happens at %ld\n", j);                return 0;  }  

It runs with output

14849324  14849260  14849196  14849132  14849068  14849004  14848940  14848876  14848812  14848748  14848684  14848620  14848556  14848492  14848428  14848364  Generation 0 collection happens at 146880  

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »