0

I use the following code

template <typename T> std::shared_ptr<T> comToShared(T* comObject) {
    comObject->AddRef();
    return std::shared_ptr<T>(comObject, [=](auto) {
        comObject->Release();
    });
}

to convert a COM object into a shared_ptr, as that fits better with the rest of my codebase. The problem is that I still can (and occasionally do) call AddRef() or Release() on the interior pointer and cause an over-release/over-retain issue.

Is there a way to hide just those two methods in this case so that using them causes a compile error whilst leaving the rest of the interface accessible?

Duncan
  • 443
  • 1
  • 5
  • 12
  • 1
    You could make `comToShared` a friend of each type COM class you want to call `comToShared` on, if the stray invocations of `AddRef` and `Release` are occurring in places that don't otherwise have access to private members of `T`. – Nathan Pierson Aug 10 '21 at 14:46
  • No. Unless you can within class declare the methods to be protected and declare a bunch of friend classes that would AddRef/Release when needed. Not sure if COM can work with that though. – ALX23z Aug 10 '21 at 14:47
  • Can just not call AddRef/Release? If needed create an additional class that calls on creation AddRef and Release on destruction - this way you'll never over- or under- release. This is similar to lock guard with mutexes. You can also just write a COM smart pointer instead of using shared ptr that will call AddRef for smart pointer instance. – ALX23z Aug 10 '21 at 14:51
  • Most COM frameworks in C++ already provide their own smart pointers for managing COM object pointers. Just as raw pointers in C++ should only be used for read-only views and smart pointers used everywhere else, the same is true in COM when used in C++. – Remy Lebeau Aug 10 '21 at 17:43

0 Answers0