Direct3D Programming Tip #3: Use Smart Pointers

Direct3D exposes functionality through COM interface pointers. Managing the reference counts on the obtained interfaces is a common problem for new Direct3D programmers. Managing the reference count on an interface becomes trivial if you use a smart pointer wrapper class, such as CComPtr<T> or boost::shared_ptr<T> and keep in mind the ownership policies established by the smart pointer class.

In addition to managing reference counts for you, smart pointers can make your code exception safe. When an exception is thrown, if an interface pointer is held within a CComPtr declared on the stack, then its destructor will be run when the stack is unwound. The destructor for CComPtr will call IUnknown::Release on any interface pointer it holds, thus cleaning up any locally obtained resources as the exception unwinds the stack to the nearest exception handler.

Read the rest of this entry »