c++c++-winrtwinrt-componentcppwinrt

Any recommendation in using smart pointers for COM-lite objects in C++/WinRT component?


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?


Solution

  • 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.

    See Microsoft Docs