オブジェクトを返すメソッドを持つ COM インターフェイスがあります。
interface ICreatorInterface {
HRESULT CreateObject( IObjectToCreate** );
};
重要なのは、呼び出しがインターフェイスICreatorInterface::CreateObject()
を実装するオブジェクトを取得する唯一の方法であるということです。IObjectToCreate
C++ では、次のようにできます。
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;
}
またはこの方法
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;
}
違いは、参照カウンターの初期化方法と、QueryInterface()
失敗した場合のオブジェクト削除の実装方法です。CCreatorInterfaceImpl
私は両方を完全にコントロールしているのでCObjectToCreateImpl
、どちらの方法でも行くことができます。
IMO 最初のバリアントはより明確です。すべての参照カウントは 1 つのコードに含まれています。私は何かを監督しましたか?なぜ 2 番目のアプローチの方が優れているのでしょうか。上記のどれがより良いですか、そしてその理由は何ですか?