Visual C ++ Unchanged and Control

What is the difference between instantiating a .NET object in C ++ that is managed or unmanaged. That is, what are the differences between these statements:

StreamWriter ^stream = gcnew StreamWriter(fileName); 

against

 StreamWriter *stream = new StreamWriter(fileName); 

My assumption is that if I use gcnew, then the memory allocated for StreamWriter will be managed by the garbage collector. Alternatively, if I use a pointer (*) and a new keyword, I will have to call delete to free the memory.

My real question is: will the garbage collector manage the memory that is allocated inside .NET objects? For example, if a .NET object creates an instance of another object and goes out of scope, will the garbage collector manage this memory even if I use a pointer (*) and a new keyword, and NOT gcnew and handle (^).

+6
memory-management pointers visual-c ++ c ++ - cli
source share
2 answers

When you create an object with gcnew , it binds to the garbage collector, and the garbage collector will be responsible for destroying it.

If you use a new one , it will not be bound to the garbage collector, and you are responsible for deleting the object.

Just clarify:
If you have a C # managed object that contains an unmanaged object inside it, the garbage collector will not delete the unmanaged object. It simply calls the managed object's destructor (if one exists) before it is deleted. You must write your own code in the destructor in order to remove the unmanaged objects that you created.

+4
source share

In C ++ / CLI you cannot new a .NET object, you get something similar to the following error:

error C2750: "System :: Object": cannot use "new" in the reference type; use gcnew instead

Using new for .NET objects is permitted in old managed extensions for C ++ ( /clr:oldsyntax compiler flag). "Managed C ++" is now deprecated because it is horrible. It was replaced by C ++ / CLI, which introduced ^ and gcnew .

In C ++ / CLI, for managed types, you should use gcnew (and ^ ), and for native types, you should use new (and * ) pointers. If you create objects in the native heap using new , your responsibility is to destroy them when you are done with them.

Ideally, you should use a smart pointer (for example, std::shared_ptr or std::unique_ptr ) to manage the object in the native heap. However, since you cannot have your own smart pointer as a field of the ref class, this is not entirely simple. The simplest and most universal approach would probably be to write your own refper refperter class that correctly implements IDisposable .

+6
source share

All Articles