As part of the Mac OS X developer library, there is a very good memory management guide for objective c. It not only describes what the various memory management functions (such as retain, autorelease and dealloc) do, but when to use each method.
For example, it has the following guidelines for releasing memory:
- You must not relinquish ownership of an object you do not own
- When you no longer need it, you must relinquish ownership of an object you own
- You can take ownership of an object using retain
- You own any object you create
It then gives detailed information about these rules, eg
You create an object using a method whose name begins with “alloc”, “new”, “copy”, or “mutableCopy” (for example, alloc, newObject, or mutableCopy).
By following these guidelines, it makes it easy for people using your code to know when they are expected to retain or release objects returned from methods and when it isn’t necessary.
Also, the guide is obviously written by people with years of experience working with objective c. So in the vast majority of cases, following the memory management guidelines would produce better code than coming up memory management guidelines yourself.
Due to these advantages, I was wondering if there was a similar guide somewhere for c++. There are many ways you can pass or return an object to a method in c++:
- by reference
- by value
- by pointer
- by
boost::shared_ptr(or other smart pointers) - const variants of the above methods
I understand how they work, but I am constantly unsure of what method I should use. There are so many different pros and cons to each method that I find I am wasting too much time deciding what method to use, only to change it later on when I find I made the wrong choice.
If I had a memory management guide for c++ like the objective c guide, it would be a much simpler job. So is there one around, either on a website or published in a book? Also, is there a set of guidelines that most c++ developers follow?
The difference is that for Objective C you are presented with a convention that is used in the standard library and that is also used practically in every program for that platform.
C++ instead is agnostic in respect to which policy you may want to use for your application and therefore there are no general rules you can follow. If you use smart pointers there are certain rules, if you use hierarchical ownership (like in Qt) there are other rules, if you use a garbage collected approach rules change again.
More or less like for hardware, problems are simpler in Apple approach because there is no variety. It’s debatable if that variety is an important resource worth fighting the included complexity or just a pointless complication.