I’m writing a C++/CLI class that needs to hold on to CComPtr for the duration of its lifefime, e.g.
public ref class MyClass
{
public:
MyClass()
{
CComPtr<ISomeType> pSomeType;
// init someType;
m_pSomeType = pSomeType;
}
private:
CComPtr<ISomeType> m_pSomeType;
void DoSomething()
{
m_pSomeType->DoSomething();
}
}
However this doesn’t compile as mixed types are not supported – the solution is to use an AutoPtr. I still need reference counting and so this is what I came up with.
public ref class MyClass
{
public:
MyClass()
{
CComPtr<ISomeType> pSomeType;
// init someType;
m_pSomeType = new CComPtr<ISomeType>(pSomeType);
}
private:
AutoPtr<CComPtr<ISomeType>> m_pSomeType;
void DoSomething()
{
CComPtr<ISomeType> pSomeType = *m_pSomeType.GetPointer();
pSomeType->DoSomething();
}
}
This looks nasty to me, and I also suspect that its wrong in some way (I come from a C# background so I’m kind of learning a lot of this as I go).
How should I “store” a CComPtr as a member of a C++/CLR class?
I’ve made a smart pointer that might help you. It can’t be used to manage COM pointers directly, but it can be used to hold a CComPtr inside a managed class.
Please respect the license requirements if you choose to use it (commercial use is not prohibited, but you must give credit).
Also, you can write
instead of copying the
CComPtr(which has to update the reference count).Besides that, I would use the ctor-initializer-list instead of assignment in the constructor.