.net 是否在托管堆上分配了Int32^i=gcnew Int32()?
基本上,我想知道.net 是否在托管堆上分配了Int32^i=gcnew Int32()?,.net,c++,new-operator,.net,C++,New Operator,基本上,我想知道 Int32^i=gcnew Int32() 和 Int32*i2=newint32() 我编写了以下代码: #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)
Int32^i=gcnew Int32()代码>
和
Int32*i2=newint32()代码>
我编写了以下代码:
#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;
}
这两个整数似乎分配在两个不同的内存位置
gcnew Int32()是否在托管堆中分配?或者直接在堆栈上?在托管C++中,< p>新分配给非托管堆,GCnew——托管堆。托管堆中的对象有资格进行垃圾收集,而非托管堆中的对象没有资格进行垃圾收集。与C类引用一样的指针,运行时跟踪它们,并使用垃圾收集,指针与普通C++指针一样工作。< /P> < P>我已经得到答案。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;
}
#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