Monday 15 February 2016

Boost Smart Pointers

Nowadays, we have the luxury of having Garbage Collectors in C#, Java, Python, etc. But we don't have that luxury in C++. Nobody can deny that managing pointers is a good to have skill, however, things had changed, the technology evolved as well and we might as well delegate the handling of pointers to someone else. Enter Boost Library. This is a superb library with lots of tools. The smart pointers on Boost library can greatly reduce the risk of memory leaks. Let's see the following samples run on Visual Studio 2015 with the memory leak detector enabled.

class ABasePerson
{
public:
    virtual void ShoutDescription() = 0;
};

class Fireman :public ABasePerson
{
public:
    void ShoutDescription()
    {
        cout << "I am a Fireman!";
    }
};


Above is a classic usage of polymorphism and we will use this as the basis of our example.
----------------------------------------------------------------------------------------------------------------
Example #1
{
ABasePerson *basePerson = new Fireman();
basePerson->ShoutDescription();
delete (basePerson);

}
This example will work well.
----------------------------------------------------------------------------------------------------------------
Example #2
{
ABasePerson *basePerson = new Fireman();
basePerson->ShoutDescription();

}
On this example, the developer forgot to delete the basePerson and now we have memory leak!
----------------------------------------------------------------------------------------------------------------
Example #3
{
boost::shared_ptr<ABasePerson> basePerson2(new Fireman());
basePerson2->ShoutDescription();
}

On this example, the basePerson2 will automatically be freed once it goes out of scope. Very convenient!
----------------------------------------------------------------------------------------------------------------
Example #4
boost::shared_ptr<ABasePerson> basePerson2(new Fireman());
basePerson2->ShoutDescription();

basePerson2 = NULL;
On this example, the basePerson2 will automatically be freed once it was set to NULL.
----------------------------------------------------------------------------------------------------------------

On this post, we saw the convenience of using Boost Smart Pointers.

Update: I am not using the Boost Smart Pointers as of the moment. Instead, I am using C++11's smart pointers since they are almost included in every compiler. (I use GCC in Linux and MSVC on Windows and they both include C++11's Smart Pointers)

No comments:

Post a Comment