I am new to c++/cli and getting confused with this new vs gcnew.
I am aware that objects created with gcnew will be garbage collected where as objects created with new are not.
Even I read somewhere that the native c++ types should be created using new. Why is it so? because we can even create native types with gcnew and forget about managing them. Won’t this be easier than managing objects with created with new?
No, native types can’t be created with
gcnew. The garbage collector needs to know every place a pointer exists to a particular object, so it can determine whether the object is reachable and adjust those pointers during compaction.Pointers to native types can be held anywhere, invisible to the garbage collector, so garbage collection isn’t possible.
However, instance of native types should rarely be created using
new. If the lifetime is limited, use a local variable or make it a class member. This isn’t Java.