在托管堆上分配Int32 ^ i = gcnew Int32()吗?

时间:2009-04-23 04:09:38

标签: .net c++ new-operator

基本上我想知道
之间的区别     Int32^ i = gcnew Int32();

   Int32* i2 = new Int32();

我写了以下代码:

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

它提供以下输出:

004158B8 0
00E1002C 0

似乎两个整数分配在两个不同的内存位置。

gcnew Int32()是否在托管堆中分配?或直接在堆栈上?

2 个答案:

答案 0 :(得分:8)

在托管C ++中, new 在非托管堆上分配 gcnew - 在托管堆上。托管堆中的对象符合垃圾回收的条件,而非托管堆中的对象则不符合。带有 ^ 的指针就像C#引用一样 - 运行时跟踪它们并用于垃圾收集,带有*的指针就像普通的C ++指针一样。

答案 1 :(得分:0)

我得到了答案。 gcnew将在托管堆上分配对象,即使类型是值类型。

因此,Int32 ^ i = 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