Generalize Smart Pointers in C++

After programming in C++ for a while, you will inevitably be introduced to the concept of “smart pointers” (or you will discover them on your own). These are pointers that know to automatically release the objects they point to when they (the pointers) are destructed. They have proved quite handy in avoiding memory leaks.

The most well known implementation of smart pointers probably is auto_ptr in STL and CAutoPtr in ATL, which will delete the object upon destruction.

auto_ptr and CAutoPtr are fine, but they have limitations:

  1. Sometimes the pointer is not allocated via the new operator (e.g. malloc()). In these cases, you don’t want to use auto_ptr or CAutoPtr as the pointer will by wrongfully deleted (as opposed to be free()-ed in the case of malloc()).
  2. They are good for wrapping pointers only. In general, you would like to allocate some resource and have the compiler release it for you automatically.

Why not generalize smart pointers to smart resource managers? It’s actually easy to do so. Here’s my take on this:

///////////////////////////////////////////////////////////

// Class CAutoResource

//

// An object of this template class holds a resource, and will dispose of

// the resource when it is destructed. This class is a generalization of

// auto_ptr in STL and CAutoPtr in ATL. The user must supply the function

// doing the disposition as a template parameter.

//

// Examples where this class can be useful include file/window/registry

// handles and pointers.

template< typename T, void (*Dispose)( T ), const T NullResource = 0>

class CAutoResource

{

public:

    typedef T ResourceType;

      CAutoResource( T Resource = NullResource )

            : m_Resource( Resource )

      {

      }

    ~CAutoResource()

    {

        if ( NullResource != m_Resource )

        {

            Dispose( m_Resource );

        }

    }

    operator T() const

    {

        return m_Resource;

    }

    T Get() const

    {

        return m_Resource;

    }

    void Attach( T NewResource )

    {

        Dispose( m_Resource );

   m_Resource = NewResource;

    }

      // The assert on operator & usually indicates a bug.

    T * operator & ()

    {

        _ASSERTE( NullResource == m_Resource );

        return & m_Resource;

    }

private:

    T m_Resource;

    CAutoResource( const CAutoResource& );

    CAutoResource& operator = ( const CAutoResource& );

};

To use the CAutoResource template class, you need to supply:

  1. The type of the resource;
  2. A function that disposes of the resource; and
  3. (Optional) The value that represents the “null” resource. If you don’t specify it, 0 is used.

Upon destruction, the resource in a CAutoResource object will be released by calling the resource disposition function.

I hope it becomes obvious to you that auto_ptr and CAutoPtr are basically special cases of CAutoResource where the disposition function is the delete operator. They do have more member functions, but those are not hard to add.

Let’s see some examples of using CAutoResource.

The first one is to wrap the generic Windows HANDLE, which is used by the Win32 API to represent a lot of different things (windows, fonts, brushes, memory, and etc). A typedef instantiates CAutoResource for this scenario:

#include <windows.h>

// Generic Windows handle

void DisposeHandle( HANDLE handle )

{

   if ( NULL != handle )

    {

        CloseHandle( handle );

    }

}

typedef CAutoResource< HANDLE, DisposeHandle > CAutoHandle;

Our second example is handle to a registry key:

// Handle to registry key

void DisposeHKey( HKEY hKey )

{

    if ( NULL != hKey )

    {

        RegCloseKey( hKey );

    }

}

typedef CAutoResource< HKEY, DisposeHKey > CAutoHKey;

Sometimes, two resources have the same C++ type but different semantics and should be released in different manners. For example, an HINTERNET should be released by either WinHttpCloseHandle() or InternetCloseHandle(), depending on whether it was allocated using the WinHttp or the WinINet API. This is no problem for us, as the disposition function is a type parameter to CAutoResource and you can specify different functions for the same C++ type:

#include <winhttp.h>

// Internet handle opened via the WinHttp API

void DisposeWinHttpHandle( HINTERNET handle )

{

    if ( NULL != handle )

    {

        WinHttpCloseHandle( handle );

    }

}

typedef CAutoResource< HINTERNET, DisposeWinHttpHandle > CAutoHWinHttp;

#include <wininet.h>

// Internet handle opened via the WinINet API

void DisposeHInternet( HINTERNET handle )

{

    if ( NULL != handle )

    {

        InternetCloseHandle( handle );

    }

}

typedef CAutoResource< HINTERNET, DisposeHInternet > CAutoHInternet;

Let’s give one example where the resource we want to manage is a pointer:

// Memory allocated via LocalAlloc() or LocalReAlloc()

void DisposeLocalMem( LPVOID lpMem )

{

    if ( NULL != lpMem )

    {

        LocalFree( lpMem );

    }

}

typedef CAutoResource< LPVOID, DisposeLocalMem > CAutoLocalMem;

So far so good, but as soon as you try to dereference a pointer masqueraded as a CAutoResource, you’ll find we haven’t defined the dereference operator (*) and the arrow operator (->) yet. This is because they don’t make sense in the context of general resources.

What we can do is to define these operators in a sub-class of CAutoResource. I would’ve called it CAutoPtr, but that name is taken, so instead we have CAutoPtrEx:

///////////////////////////////////////////////////////////

// Class CAutoPtrEx

//

// An object of this template class holds a pointer, and will dispose of

// the object pointed to when it is destructed. This class is a

// generalization of auto_ptr in STL and CAutoPtr in ATL.

// It is preferred to auto_ptr and CAutoPtr when 'delete' is not the right

// way to dispose of the object. The user must supply the function doing

// the disposition as a template parameter.

template< typename T, void (*Dispose)( T * ) >

class CAutoPtrEx : public CAutoResource< T *, Dispose, NULL >

{

public:

    CAutoPtrEx( T * ptr = NULL )

        : CAutoResource< T *, Dispose >( ptr )

    {}

    T& operator * () const

    {

        return *Get();

  }

    T * operator -> () const

    {

        return Get();

    }

private:

    CAutoPtrEx( const CAutoPtrEx& );

    CAutoPtrEx& operator = ( const CAutoPtrEx& );

};

I’ll finish this article with an example using CAutoPtrEx:

// Memory allocated via CoTaskMemAlloc() or CoTaskMemRealloc()

template <typename T>

class CComMem

{

public:

    static void Dispose( T * pMem )

    {

        if ( pMem )

        {

            ::CoTaskMemFree( pMem );

        }

    }

    typedef CAutoPtrEx< T, CComMem::Dispose > AutoPtr;

};

(This posting is provided "AS IS" with no warranties, and confers no rights.)