Click here to Skip to main content
15,867,704 members
Articles / Programming Languages / C++

Scheming Code: The Dispose Pattern in C++

Rate me:
Please Sign up or sign in to vote.
5.00/5 (1 vote)
8 Mar 2012CPOL3 min read 27.4K   6   7
Dispose pattern in C++

Welcome to the first article in the Scheming Code series. The series is meant to be a focus on the creation of various patterns in various programming languages. This particular article will describe the Dispose pattern, and how to employ it in C++. Please note: This is not an introduction to C++. The topics and code presented here are done so with the assumption that the reader knows how to write basic data structures in C++. Also, with most of my background in .NET, C++ best practices are followed to the extent of my abilities.

Why Not Just Use the Destructor?

It is written [MSDN: Implementing a Dispose Method], “the pattern for disposing an object, referred to as a dispose pattern, imposes order on the lifetime of an object.” Using the Dispose pattern, the developer can determine when an object is destroyed. In .NET, it is generally only used for objects that access unmanaged resources. Since C++ is unmanaged, memory management is our priority and responsibility. One of the points this gets to is properly destroying objects. Memory leaks can occur when improperly destroying objects (or when failing to destroy them). I, along with many other developers, cannot prevent 100% of memory leaks. We can take measures to get as close to that point as possible but, odds are there will be at least one somewhere in the vastness of the code. One measure that can be taken is implementing the Dispose pattern and using it appropriately. It makes managing memory more explicit and allows for a higher-level mechanism for managing an object’s lifetime.

How is it Done in .NET?

Implementing the Dispose pattern in .NET requires deriving from System.IDisposable:

C#
public interface IDisposable
{
    void Dispose();
}
public sealed class DisposableObject : IDisposable
{
    private bool _disposing;
    public override Dispose()
    {
        this.Dispose(!this._disposing);
        GC.SuppressFinalize(this);
    }
    private void Dispose(bool disposing)
    {
        if(disposing)
        {
            this._disposing = true;
            //… release resources here …
        }
    }
}

Implementing the dispose pattern in this way basically marks the object as “dead”. By doing this, it allows the Garbage Collector to free the memory used by the object without the need to perform costly finalization. It is best practice to create a protected (or private if the class is not inheritable) dispose method accepting a boolean value indicating if the object is disposing. Doing this allows further control of object disposal.

Proper OOD (Object-Oriented Design) is employed here by separating the interface from its implementation (please see the Separation PDF). Microsoft did well with this one. With the IDisposable interface, multiple objects can be “Disposable” and mechanisms can be created to track these kinds of objects.

How is it Done in C++?

In C++, the Dispose pattern is used to explicitly release resources used by the internals of the object. To properly implement this, an interface must be created:

C++
public class IDisposable
{
    void dispose() = 0;
};

This looks much like the interface in .NET but with a few C++ semantics to enforce what we are intending. By making the dispose() method virtual, we force the user of this interface to implement it in their subclass:

C++
public class DisposableObject : public IDisposable
{
    private bool _disposing;
    public override dispose()
    {
        if(this.dispose(!this->_disposing))
        {
            //… more disposing-dependent logic here …
        }
    }
    protected bool dispose(bool disposing)
    {
        if(disposing)
        {
            this->_disposing = true;
            //… release resources here …
        }
        return this->_disposing;
    }
};

Again, this looks a lot like the .NET version, but with a few changes for C++ compliance. The code also includes a variation of the protected dispose method to demonstrate the ability for even further disposal control.

How is it Used in C++?

Generally, the dispose method is called within the object’s destructor. By tracking whether the object is disposed or not, other tracking mechanisms can be used to explicitly dispose the object. Below is a basic custom auto_ptr implementation created based on various sources (A Sample auto_ptr implementation, Scott Meyers Update on auto_ptr):

C++
template<typename TObject, typename R, R (TObject::*Dispose)()>
class AutoPtr
{
public:

	explicit AutoPtr(TObject* pointerToWrap = NULL)
		: wrapper(pointerToWrap)
	{
	}

	AutoPtr(AutoPtr& Other)
		: wrapper(Other.Release())
	{
	}

	AutoPtr& operator=(AutoPtr& Other)
	{
		Reset(Other.Release());
		return (*this);
	}

	~AutoPtr()
	{
		if(wrapper)
		{
			(wrapper->*Dispose)();
			wrapper = NULL;
		}
	}

	TObject& operator*() const
	{
		return (*wrapper);
	}

	TObject** operator&()
	{
		Reset();
		return &wrapper;
	}

	TObject* operator->() const
	{
		return GetPointer();
	}

	operator bool() const
	{
		return wrapper != NULL;
	}

	TObject* GetPointer() const
	{
		return wrapper;
	}

	TObject* Release()
	{
		TObject* tempPtr = wrapper;
		wrapper = NULL;
		return tempPtr;
	}

	void Reset(TObject* p = NULL)
	{
		if(p != wrapper)
		{
			if(wrapper)
			{
				(wrapper->*Dispose)();
			}
		}

		wrapper = p;
	}

private:
	TObject* wrapper; //the wrapped pointer
};

With this code, we can do something like:

C++
typedef AutoPtr<DisposableObject, void, &DisposableObject::Dispose> DisposablePtr;

And use it like this (note that “work” is assumed to be an instance method of DisposableObject):

C++
DisposablePtr obj(new DisposableObject());
obj->work();

Above is an AutoPtr implementation that automatically disposes objects when the AutoPtr instance goes out of scope. This is an example of a high-level mechanism of memory management making good use of the Dispose pattern.

Conclusion

This was an exhaustive look at how the Dispose pattern can be implemented in C++ to encourage easier memory management. First, the .NET version of the pattern was examined. Then, moving on to C++, the Dispose pattern was implemented and then used in a custom auto_ptr implementation. Memory management is a very important aspect of C++. This article describes one way to make it a little easier.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer
United States United States
Caleb is a software development consultant specialized in creating web solutions for critical business problems. He has a passion for front-end development and helping other developers find their role. He enjoys making development easier to do, easier to learn and easier to improve upon. His days are pleasantly filled with TypeScript, HTML5 and C#.

Comments and Discussions

 
QuestionGreat article! Pin
ely_bob9-Mar-12 4:48
professionalely_bob9-Mar-12 4:48 
This approach is used in gameing, where you would want to handle the graphics memory differently then the motherboard memory.. .very clear thanks. Shucks | :-\

I'd blame it on the Brain farts.. But let's be honest, it really is more like a Methane factory between my ears some days then it is anything else...

-----

"The conversations he was having with himself were becoming ominous."-.. On the radio...




GeneralRe: Great article! Pin
Caleb McElrath9-Mar-12 4:58
professionalCaleb McElrath9-Mar-12 4:58 
AnswerRe: Great article! Pin
N-O-R-B-E-R-T11-Mar-12 22:44
N-O-R-B-E-R-T11-Mar-12 22:44 
QuestionWhat's wrong with RAII? Pin
Pablo Aliskevicius8-Mar-12 4:03
Pablo Aliskevicius8-Mar-12 4:03 
AnswerRe: What's wrong with RAII? Pin
Caleb McElrath8-Mar-12 7:08
professionalCaleb McElrath8-Mar-12 7:08 
QuestionRe: What's wrong with RAII? Pin
Samuel Cragg8-Mar-12 22:49
Samuel Cragg8-Mar-12 22:49 
AnswerRe: What's wrong with RAII? Pin
JackGrinningCat19-Apr-17 23:56
JackGrinningCat19-Apr-17 23:56 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.