This is a mirror of official site: http://jasper-net.blogspot.com/

C++ Productivity: Memory Management 101 for the .NET Guy

| Monday, June 6, 2011
I wanted to start what hopefully will become a series on C++ productivity that is geared towards .NET developers that have had at least some (maybe painful) experience with C++.  The first topic I’m covering is memory management as this area is often cited as the killer reason to use a garbage collected runtime over a native language like C++.

“My code has ninety-nine problems, but memory management should not be one.”

Fair enough.  Developing code is hard.  Developing code that is stable and doesn’t leak like a sieve is even harder.  Even in .NET we fight “leaks”, but as we became masters of the runtime we remembered simple rules to avoiding leaks in our managed application such as:

  • Being mindful of a hooked event, making sure it is unhooked if the object lifetime of the observer is shorter than the subject.
  • Static objects are rooted.  Objects that static objects refers to are also rooted.
  • Dispose an IDisposable or make use of the using statement.
  • Be aware of framework deficiencies (like this one from WPF)
Being masters of the .NET runtime, rules like these are second nature to us.  What about C++ where we directly allocate/deallocate memory?  How much more difficult is it than .NET?  Depending on your point of view, some say it’s easier.  Just like .NET, you just have to remember some simple rules.  I’ll explain as I go along, but first some background…

C++, Dynamic Memory and Automatic Variables

Apologies if this next part is rehash from computer science, but bear with me as it contains some important concepts.  I won’t go too far in depth as there are thousands of smarter folks that have covered this far better than I.  In C++ you have dynamically allocated variables and automatic variables.  The distinction is very simple.  Dynamic means you created something using the new keyword and will look like a pointer.  Automatic means the new keyword was not used.

Here is an example of a class that uses dynamically allocated memory:

CMyClass* pClass = new CMyClass();
pClass->DoSomething();

Notice here that pClass is a pointer type.  When we instantiate it with the new keyword, memory is allocated on the heap and that memory location is assigned to pClass.  This memory will not be freed unless we execute delete pClass.

Here is an example of an automatic variable:

CMyClass myClass;
myClass.DoSomething();

Read more: Jer's Hacks

Posted via email from Jasper-net

0 comments: