I have a COM interface with a method that returns an object:
interface ICreatorInterface {
HRESULT CreateObject( IObjectToCreate** );
};
The key is that calling ICreatorInterface::CreateObject()
is the only way to retrieve an object implementing IObjectToCreate
interface.
In C++ I could do it this way:
HRESULT CCreatorInterfaceImpl::CreateObject( IObjectToCreate** result )
{
//CObjectToCreateImpl constructor sets reference count to 0
CObjectToCreateImpl* newObject = new CObjectToCreateImpl();
HRESULT hr = newObject->QueryInterface( __uuidof(IObjectToCreate), (void**)result );
if( FAILED(hr) ) {
delete newObject;
}
return hr;
}
or this way
HRESULT CCreatorInterfaceImpl::CreateObject( IObjectToCreate** result )
{
//CObjectToCreateImpl constructor sets reference count to 1
CObjectToCreateImpl* newObject = new CObjectToCreateImpl();
HRESULT hr = newObject->QueryInterface( __uuidof(IObjectToCreate), (void**)result );
// if QI() failed reference count is still 1 so this will delete the object
newObject->Release();
return hr;
}
The difference is how the reference counter is initialized and how the object deletion is implemented in case QueryInterface()
fails. Since I fully control both CCreatorInterfaceImpl
and CObjectToCreateImpl
I can go either of ways.
IMO the first variant is clearer - all reference-counting stuff is in one piece of code. Have I overseen something? Why could the second approach be better? Which of the above is better and why?