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 get an object that implements the IObjectToCreate interface.
In C ++, I could do it like this:
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 in 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 is deleted if QueryInterface() fails. Since I have full control over both CCreatorInterfaceImpl and CObjectToCreateImpl , I can go either way.
IMO the first option is clearer - all elements of reference counting are in one piece of code. Am I in control of something? Why could the second approach be better? Which of the above and why?
source share