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

Collect your C++ Garbage with Boost

| Thursday, September 2, 2010
  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;

}

Read more: Libzter

Posted via email from .NET Info

0 comments: