将智能指针分配给_variant_t是否需要手动AddRef()?

发布于 2024-12-05 19:27:56 字数 404 浏览 3 评论 0原文

这是一个示例片段:

_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());

你的想法?

Here is an example snippet:

_variant_t var;

var.vt = VT_UNKNOWN;

var.punkVal = unknownInterfaceSmartPointer;

unknownInterfaceSmartPointer->AddRef(); // Question Statement

// Setting unknownInterfaceSmartPointer to some other container

Whether manual AddRef is really needed here? Following will is better way than this:

_variant_t var(unknownInterfaceSmartPointer.GetInterfacePointer());

your thoughts?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

世界等同你 2024-12-12 19:27:56

如果您直接分配给 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();

If you directly assign to punkVal member (as in your first snippet) then you need an AddRef() - noone will do it for you. A much better way would be to use operator=() member of _variant_t:

_variant_t var;
var = unknownInterfaceSmartPointer.GetInterfacePointer();

or do as you suggest - use a conversion constructor:

_variant_t var(unknownInterfaceSmartPointer.GetInterfacePointer());

Both latter variants are good and don't require an AddRef() in your code - it will be done inside _variant_t implementation. Furthermore, they are beneficial because if you reassign to the same variant the implementation will do proper cleanup for you:

_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();
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文