How to use shared_ptr for COM interface pointers

Posted by Seefer on Game Development See other posts from Game Development or by Seefer
Published on 2012-10-28T00:22:05Z Indexed on 2012/10/28 11:23 UTC
Read the original article Hit count: 383

Filed under:

I've been reading about various usage advice relating to the new c++ standard smart pointers unique_ptr, shared_ptr and weak_ptr and generally 'grok' what they are about when I'm writing my own code that declares and consumes them.

However, all the discussions I've read seem restricted to this simple usage situation where the programmer is using smart in his/her own code, with no real discussion on techniques when having to work with libraries that expect raw pointers or other types of 'smart pointers' such as COM interface pointers.

Specifically I'm learning my way through C++ by attempting to get a standard Win32 real-time game loop up and running that uses Direct2D & DirectWrite to render text to the display showing frames per second.

My first task with Direct2D is in creating a Direct2D Factory object with the following code from the Direct2D examples on MSDN:

ID2D1Factory* pD2DFactory = nullptr;
HRESULT hr = D2D1CreateFactory(D2D1_FACTORY_TYPE_SINGLE_THREADED, &pD2DFactory);

pD2DFactory is obviously an 'out' parameter and it's here where I become uncertain how to make use of smart pointers in this context, if indeed it's possible. My inexperienced C++ mind tells me I have two problems:

  1. With pD2DFactory being a COM interface pointer type, how would smart_ptr work with the Add() / Release() member functions for a COM object instance?
  2. Are smart pointers able to be passed to functions in situations where the function is using an 'out' pointer parameter technique?

I did experiment with the alternative of using _com_ptr_t in the comip.h header file to help with pointer lifetime management and declared the pD2DFactory pointer with the following code:

_com_ptr_t<_com_IIID<pD2DFactory, &__uuidof(pD2DFactory)>> pD2DFactory = nullptr;

and it appears to work so far but, as you can see, the syntax is cumbersome :)

So, I was wondering if any C++ gurus here could confirm whether smart pointers are able to help in cases like this and provide examples of usage, or point me to more in-depth discussions of smart pointer usage when needing to work with other code libraries that know nothing of them. Or is it simply a case of my trying to use the wrong tool for the job? :)

© Game Development or respective owner

Related posts about c++