C++ tip 9: Use objects to manage resources

Hello again.

Today I want to share a very important tip that I learned from Effective C++ that would minimize your memory leaks in your application. It is about Managing Resources.

In C++, the most commonly used resource is dynamically allocated memory. As you know, if you allocate memory and never deallocate it, you will have memory leaks.

So once you finished using a resource, you must release it.

The problem is that doing this manually is usually not a good idea. For example, take a look at the function below:

void main(){
    //createPolygon is a factory method which returns a pointer to dynamically allocated Polygon object 
    Polygon *pPoly=createPolygon();

    //...

    //release the object
    delete pPoly;
}

The example above seems to be OK. The problem is that there is no guarantee that the line of code delete would ever execute. In between the creation of the object and the deletion, there may be some exceptions that throw or some premature return statements. Thus, never releasing the object.

A better idea is to place those resources inside objects whose destructors will automatically release the objects.

C++ offer two of these objects. The first one is the autoptr. The _autoptr_ is a pointer-like object whose destructor automatically calls delete on what is pointing to.

Below is an example on how you would use it:

void main(){
    //1. Give the resource upon creation to auto_ptr
    std::auto_ptr<polygon> pPoly(createPolygon());

    //...
} //2. upon exit, automatically delete pPoly via auto_ptr destructor

According to Scott Meyers, this demonstrates two important concepts:

  • Resources are acquired and immediately turned over to resource-managing objects (as shown in line 1).
  • Resource-managing objects use their destructors to ensure that resources are released (as shown in line 2).

There is an alternative to autoptr. This alternative is called _Reference-counting smart pointer (RCSP). Meyers states that a RCSP is a smart pointer that keeps track of how many objects point to a particular resource and automatically deletes the resource when nothing is pointing to it.

An example of a RCSP is shared_ptr. Below is an example:

void main(){
    //1. Give the resource upon creation to auto_ptr
    std::tr1::shared_ptr<polygon> pPoly(createPolygon());

    //...
} //2. upon exit, automatically delete pPoly via shared_ptr destructor

So the point is the following:

Don't try to manage resources manually instead use objects (autoptr or tr1::sharedptr) to help you manage resources.

If you want to get new tips on game engine development and C++ sign up to my newsletter below.

Harold Serrano

Computer Graphics Enthusiast. Currently developing a 3D Game Engine.