C++ do not have automatic garbage collection built in like Java, .NET languages as well as many others. This has its pros and cons since the gained freedom will lead to potential memory leaks and a lot of extra code to deal with clean up.
Using the boost library, specifically the smart pointers provided, most of the memory handeling burden can be lift of the programmes shoulders.
In the boost library, there is an object, shared_ptr, that you can use to wrap all your pointers to which you have allocated memory. The shared pointer will keep track of all references to the very object, and once the final pointer to the objects gets out of scope or deleted, then your object will be freed automatically.
Here is some code that shows how to use boost::shared_ptr together
with STL containers. Note that no "delete" keyword is used in the code.
#include <boost/shared_ptr.hpp>
#include <iostream>
#include <vector>
// Just a simple class
class Foo{
public:
Foo(){ }
~Foo(){
std::cout << "Destructing. " << (int)this << std::endl;
}
};
// Make shorthand to cut some typing
typedef boost::shared_ptr<Foo> FooPtr;
// this functions allocates memory for an object, return a shared_ptr to it and forgets about it.
FooPtr CreateFoo(){
FooPtr fp(new Foo);
return fp;
}
int main(int argc, char** argv){
std::vector<FooPtr> foos;
foos.push_back(CreateFoo());
foos.push_back(CreateFoo());
FooPtr temp = foos[1]; // extract the second object
std::cout << "clearing vector.." << std::endl;
foos.clear(); // the first object will be deleted here, but not the second, since it has a reference still in scope.
std::cout << "ending program.." << std::endl;
// main returns and the final object goes out of scope and is automatically destroyed.
return 0;
}
Is this a complete garbage collection? The answer is no. If you use shared_ptr to wrap objects everytime you allocate a new object, then the risk for memory leaks are pretty much removed. However, with third pary libraries that does not use boost::shared_ptr, you might have to resort to manual memory management for parts of your code. The real up side of this approach is that you can choose which objects should be memory managed automatically and which should manually managed. Put your time and effort to the parts of the code that is close to hardware or is performance critical - high level code should really be high level.