Resource Management

Here is a very simple resource-management class that I've been using on my current project at work. It is designed to be a very basic and generic way to ensure that resources are closed predictably.

The Resource class

Ever since I was first introduced to the Resource Acquisition Is Initialization idiom, I've been a big fan. When applied to pointers it's a terrific way to prevent memory leaks, and it's useful for other kinds of resources as well.

I wanted to make a very simple template to allow me to apply RAII to various kinds of resources simply and generically. I came up with a class like the following:

template<typename T> class Resource
{
public:
    Resource(T t) : t(t)
    {
    }

    ~Resource()
    {
        Free();
    }

    // No implementation!
    void Free();

private:
    // The actual resource
    T t;

    // I disallow the following methods for simplicity's sake
    Resource();
    Resource(const Resource&);
    Resource& operator=(const Resource&);
};

What this template does is generate a class for each unique type T that takes a copy of the resource to be managed when it is created, and calls a method to free that resource when it is destroyed. Note that there is no default implementation for the Free() method. This implementation must be provided for each specific type of resource.

Using the Class

Here is how I might use the class to manage a couple of different resources.

// Template specializations for freeing file handles. 
void Resource<FILE*>::Free()
{
    fclose(t);
}

int main()
{
    FILE* f = fopen("foo.txt", ”r”);
    
    if (f)
    {
        Resource<FILE*> rf(f);
        // use f
    }
    
    // file is guaranteed to be closed when rf goes out of scope.
    
    return 0;
}

In this example I want to make sure that any valid file handle returned by fopen will always be properly closed. I provide an implementation of the Free() method for FILE* specializations of the Resource template. This method will be called by the destructor of any object of type Resource<FILE*>.