这是一个示例片段:
_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());
你的想法?
最佳答案
如果您直接分配给punkVal
成员(如第一个代码段中所示),则您需要一个AddRef()
-没有人会为您做这件事。更好的方法是使用operator=()
的_variant_t
成员:
_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();