What is the difference between C++ memory management and .NET memory management ?
What is the difference between C++ memory management and .NET memory management ?
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
In C++, you can either allocate objects with static storage so they are around for the whole program, allocate them on the stack when they are local to a function (in which case they are destroyed when the containing block exits), or allocate them on the heap (in which case they are only destroyed when you say so by explicitly calling the appropriate de-allocation function). Heap memory is allocated as raw memory with
mallocand released withfree, or allocated and constructed into an object withnew, and then the object destroyed and the memory released withdelete.C# provides an illusion of infinite memory — you cannot free memory explicitly, only allocate memory and construct an object with
new. Instead the GC reclaims the memory for objects you can no longer access so that it can be reused for new objects.In C++, class destructors are run when an object is destroyed. This gives each object a chance to release any associated resources whether they are more objects, or external resources such as file handles or database handles.
In C#, you must explicitly manage the release of non-memory resources by calling a release function. The
usingfacility allows you to get the compiler to callDispose()automatically for you, but this is still separate from the object lifetime — the memory for the object is reclaimed when the GC system decides to (which may be never).In C++, facilities like
std::shared_ptr(orboost::shared_ptrwith older compilers) allow you to pass the responsibility of destroying heap objects over to the C++ runtime by reference-counting the objects. When the last instance ofshared_ptrthat references a given object is destroyed, then the referenced object is destroyed too and its memory reclaimed. This avoids many of the pitfalls associated with manual memory management.