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

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

I wrote 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 result:

004158B8 0
00E1002C 0

It seems that two integers are allocated in two different memory cells.

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

+3
source share
2 answers

In managed C ++ new, an unmanaged heap is allocated, gcnew on a managed heap. Objects in the managed heap have the right to garbage collection, and objects in the unmanaged heap are not. Pointers with ^ work like C # links - the runtime tracks them and uses them for garbage collection, pointers with * work like normal C ++ pointers.

+8

. gcnew , - .

, Int32 ^ = gcnew Int32() .

:

#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;
}

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

Source: https://habr.com/ru/post/1706938/


All Articles