2011-09-21 53 views
1

下面是一個例子片段:是否將智能指針分配給_variant_t需要手動AddRef()?

_variant_t var; 

var.vt = VT_UNKNOWN; 

var.punkVal = unknownInterfaceSmartPointer; 

unknownInterfaceSmartPointer->AddRef(); // Question Statement 

// Setting unknownInterfaceSmartPointer to some other container 

是否真的在這裏需要手動的AddRef?以下將是比這更好的方式:

_variant_t var(unknownInterfaceSmartPointer.GetInterfacePointer()); 

你的想法?

回答

1

如果你直接分配給punkVal成員(如你的第一個片段),那麼你需要一個AddRef() - 沒有人會爲你做。更好的方法是使用會員的_variant_toperator=()

_variant_t var; 
var = unknownInterfaceSmartPointer.GetInterfacePointer(); 

或做你的建議 - 使用轉換構造函數:

_variant_t var(unknownInterfaceSmartPointer.GetInterfacePointer()); 

兩個變種後者是好的,不需要AddRef()在你的代碼中 - 它將在_variant_t實現中完成。此外,他們是有益的,因爲如果你重新分配到相同的變種實施將做適當的清理你:

_variant_t var; 
// if you assign a BSTR or smart pointer here 
// you want it to be properly released later 
var = whatever1(); 
// this will do the proper release of the previously 
// stored stuff and then assign the new value 
var = whatever2(); 
+0

很好,謝謝.. – AksharRoop