See what's going on with flipcode!




This section of the archives stores flipcode's complete Developer Toolbox collection, featuring a variety of mini-articles and source code contributions from our readers.

 

  Typesafe Safe Release Function
  Submitted by



I'm working with DirectX (and C++), and, to clean up after myself, I often write code like this:

if(m_pVertexBuffer)
{
	m_pVertexBuffer-Release();
	m_pvertexBuffer = 0;
}
  

Although DxUtil.h contains a SAFE_RELEASE macro that does just that, I try to avoid using macros when possible.

I thought that making a function to do this would be trivial, as all COM interfaces can be passed as an IUnknown pointer. I tried passing a pointer to a pointer and a reference to a pointer, but I could not come up with a polymorphic function that worked.

Finally, I came up with this templated function.

// Global safe release templated function
template <class T
void SafeRelease(T& IUnk)
{
	if (IUnk)
	{
		IUnk-Release();
		IUnk = 0;
	}
}
  



It works beautifully. Now, to safely release my vertex buffer, all I have to do is:

SafeRelease(m_pVertexBuffer); 



I don't even have to tell it what type m_pVertexBuffer is, because the compiler can determine that at compile-time and instantiate the correct SafeRelease function.

Furthermore, due to the way SafeRelease is written, it will even work with objects that are not COM interfaces. Call SafeRelease on any pointer to an object of a class with a Release method, and it will work like a charm. It's typesafe, too. If you call it on an object that does not have a Release method, you will get a compile-time error.

Elegant? I like it.

I'm happy to hear any comments or suggestions.


The zip file viewer built into the Developer Toolbox made use of the zlib library, as well as the zlibdll source additions.

 

Copyright 1999-2008 (C) FLIPCODE.COM and/or the original content author(s). All rights reserved.
Please read our Terms, Conditions, and Privacy information.