Ghita
Ghita

Reputation: 4505

ATL CComPtr copy constructor

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().

Upvotes: 1

Views: 1948

Answers (1)

sharptooth
sharptooth

Reputation: 170519

Yes, you implement it in one of the clearest ways. You'd have to store the last returned value somewhere - for example in CConfig as 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 be AddRef()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 (call AddRef() at least once).

So your code does it right - it copies a stored pointer and does AddRef(). You could just as well go without CComPtr:

if (pVal == nullptr) {
    return E_POINTER;
}

*pVal = this->obj;
if( this->obj != 0 ) {
   this->obj->AddRef();
}
return S_OK;

Upvotes: 1

Related Questions