C++/WinRT provides 3 flavors of smart pointers to use for COM objects - Microsoft::WRL::ComPtr
, com_ptr
, and ATL-based CComPtr
.
In my case, it is a COM-lite object, meaning it is NOT an in-proc or out-of-proc COM object, it is created as a C++ object.
In that case, which smart pointer should I use in a C++/WinRT component?
Whether using "true COM" or "COM lite" (a.k.a. "nano-COM"), you track the lifetime the same way using the IUnknown
methods AddRef and Release. The various COM smart-pointers all rely on the IUnknown
methods, so you can you whichever one you want.
For C++/WinRT applications, the recommendation is to use winrt::com_ptr
. For more information, see Consume COM components with C++/WinRT on Microsoft Docs.
I personally prefer to use Microsoft::WRL::ComPtr in all my code because my projects generally support UWP using C++/CX, UWP using C++/WinRT, Xbox using the XDK via C++/CX, Xbox using the XDK via C++/WinRT, Xbox using the GDK, and Win32 desktop platforms.
The WRL ComPtr works for Windows Runtime applications using C++/CX or C++/WinRT.
WRL ComPtr works for Win32 classic desktop applications on older versions of Windows as well. You can use #include <wrl/client.h>
to get just this class, and if you make no use at all of Windows Runtime APIs you can also define both __WRL_NO_DEFAULT_LIB__
and __WRL_CLASSIC_COM_STRICT__
preprocessor defines.
WRL ships in the Windows 8.0 SDK, Windows 8.1 SDK, Windows 10 SDK, and Xbox One XDK. This means it's available all the way back to Visual Studio 2012.
It's a better option than the older ATL CComPtr
. WRL is essentially "ATL 2.0" so a number of subtle usage issue have been fixed. See this MSDN Magazine Article.
There are also some quirks about where ATL was made available. In Visual Studio "Express" editions, ATL/MFC were not included as they were considered "Professional" features. The VS 2012 and VS 2013 versions of the Express SKUs all had the Windows 8.x SDK, so they included WRL but not ATL. FWIW, the Community editions don't have this issue.
See Microsoft Docs