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
wil::com_ptr
as well. The templates are doing the same thing, so your rule of thumb is not not mix libraries for no reason. If you are developing a project based on C++/WinRT then prefer its templates. – KuduCComPtr
, Visual Studio's_com_ptr_t
, WRL'sComPtr
, C++/WinRT'scom_ptr
, and WIL'scom_ptr
. All of those implementations do in fact have dependencies, with the exception of C++/WinRT's that only requires a C++17 compiler (in theory, anyway). – Saudra