I read about various usage tips related to the new standard C ++ smart pointers unique_ptr, shared_ptr and weak_ptr and usually "grok", which they refer to when I write my own code that declares and consumes them.
However, all the discussions that I read are apparently limited to this simple use case when a programmer uses smart in his own code, without a real discussion about methods when you have to work with libraries that expect raw pointers or other types of smart pointers "such as COM interface pointers.
In particular, I am learning my way through C ++, trying to get a standard Win32 game loop in real time, which uses Direct2D and DirectWrite to render text to a display showing frames per second.
My first task with Direct2D is to create 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 here I am becoming uncertain how to use smart pointers in this context, if it is really possible. My inexperienced C ++ mind tells me that I have two problems:
- With pD2DFactory being a type of COM interface pointer, how would smart_ptr work with the Add () / Release () member functions for an instance of a COM object?
- Is it possible to pass smart pointers to functions in situations when a function uses the "out" pointer parameter method?
I experimented with an alternative to using _com_ptr_t in the comip.h header file to help in managing the pointer's life cycle and declaring a pD2DFactory pointer with the following code:
_com_ptr_t<_com_IIID<pD2DFactory, &__uuidof(pD2DFactory)>> pD2DFactory = nullptr;
and it seems to work so far, but as you can see, the syntax is cumbersome :)
So, I was wondering if any C ++ gurus can confirm whether smart pointers can help in such cases and provide usage examples, or point me to more detailed discussions on using smart pointers when you need to work with other code libraries, who donβt know anything about them. Or is it just the case when I try to use the wrong tool to work? :)