3

基本上我想知道和之间的
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() 是否分配在托管堆中?还是直接在堆栈上?

4

2 回答 2

8

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

于 2009-04-23T04:14:54.743 回答
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
于 2009-04-23T04:19:17.027 回答