I use on my COM server simple object constructor:
CComPtr<IObj> obj; //member
hr = SUCCEDDED(hr) ? this->obj.CoCreateInstance(__uuidof(CObj)) : hr;
STDMETHODIMP CConfig::get_Obj(IObj ** pVal)
{
if (pVal == nullptr)
{
return E_POINTER;
}
CComPtr<IObj> result(this->obj);
*pVal = result.Detach();
return S_OK;
}
What I want to accomplish is for the get_Obj() method to return same interface object at succesive calls. Looking over the code CComPtr seems to increment reference count. I also detach afterwards from CComPtr.
Is this the right way to implement what I want ? I don’t want the COM client to be forced to “dispose” the IObj interface object every time it calls method get_Obj().
Yes, you implement it in one of the clearest ways. You’d have to store the last returned value somewhere – for example in
CConfigas a member variable. Other than that you can’t provide clean onwership semantics – it’s normal that the client will expect the returned pointer to beAddRef()ed (as in your code) and it’s normal that the client will release the object ownership. If you want to return the same object you have to store an extra pointer somewhere and that pointer must also own the object (callAddRef()at least once).So your code does it right – it copies a stored pointer and does
AddRef(). You could just as well go withoutCComPtr: