http://social.msdn.microsoft.com/forums/en-US/vclanguage/thread/a10e4f13-6167-4f1a-bba6-c6010cdf6f89
The new
and gcnew
operator are similar. Both allocate memory and invoke the constructor of the object. Whereas new
allocates memory from a native heap and returns a pointer, gcnew
will allocate memory from the GC heap and return a handle. A boxed value type is easy to recognize, as the type is simply a handle to value type. For example:
int m = 42; // integer on the stack
int* n = new int(42); // integer on a native heap
int^ o = gcnew int(42); // boxed integer on the GC heap
There are other ways to create boxed value types, but I will leave that for another time when I discuss the implementation of boxed value types.
Why is it important to distinguish whether an instance of an object is on the GC heap or a native heap? The GC algorithm implemented by the CLR is a generational compacting garbage collector. This means that the memory location of the object can change upon each garbage collection. This does not happen on the native heap. A pointer refers to an instance in memory that never moves. The garbage collector ensures that a handle always points to the right instance.
No comments:
Post a Comment