C++ std::auto_ptr 复制构造函数

发布于 2024-09-28 08:20:40 字数 100 浏览 11 评论 0原文

std::auto_ptr 缺少 const 复制构造函数,因此我无法直接在集合中使用它。有没有办法在不使用 boost 指针集合模板的情况下获得例如 std::auto_ptr 向量?

std::auto_ptr lacks const copy constructor, therefore I cannot use it directly in collections. is there some way to have for example vector of std::auto_ptr without using boost pointer collection template?

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

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

发布评论

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

评论(3

总攻大人 2024-10-05 08:20:40

如果您有 C++0x 编译器,则可以根据需要使用 shared_ptrunique_ptr

此处有一个正确使用 unique_ptr 的好例子@詹姆斯·麦克内利斯。如需 shared_ptr 演练,请查看此处,由 @D 提供.肖利。 [我相信,在这些线程上仍然会受到赞赏。]

auto_ptrvector 始终无效,尽管 Visual C++ v6 不同意。

If you have a C++0x compiler you can use shared_ptr or unique_ptr as appropriate.

There is a good example of correct unique_ptr usage here courtesy of @James McNellis. For a shared_ptr walkthrough look here, courtesy of @D.Shawley. [Upvotes would still be appreciated on those threads, I am sure.]

vector of auto_ptr is always invalid, although Visual C++ v6 disagreed.

你另情深 2024-10-05 08:20:40

不,你只是不能拥有 std::auto_ptr 向量,尽管有很多猜测可以。但是,如果您的编译器支持 C++0x,则可以使用 std::unique_ptr,这是已弃用的自动指针的新替代方案,引用新标准,它提供了更好的替代方案。另请参阅此帖子

No, you just can't have a vector of std::auto_ptr, though there exist many speculations that you can. But if your compiler supports C++0x, you can use std::unique_ptr, which is the new alternative of the deprecated auto pointer which, quote from the new standard, provides a superior alternative. See also this thread

甜味超标? 2024-10-05 08:20:40

auto_ptr 设计用于当变量离开作用域时自动删除。你不想在集合中使用它,而是如上所述,你想使用像shared_ptr这样的东西。

auto_ptr 的典型用途示例:

void foo()
{
   auto_ptr<int> bar = auto_ptr<int>(new int);
   ...

   return;  //memory held by auto_ptr is automatically deleted
}

如果您不确定 auto_ptr 的特殊语义,超出此用途的任何内容都可能存在危险和/或损坏。 (编辑:根据阿门的评论进行澄清)

auto_ptr is designed for auto deletion when a variable leaves scope. You don't want to use it in a collection, instead as mentioned above you want to use something like shared_ptr.

Example of auto_ptr's typical use:

void foo()
{
   auto_ptr<int> bar = auto_ptr<int>(new int);
   ...

   return;  //memory held by auto_ptr is automatically deleted
}

Anything beyond this use is potentially dangerous and/or broken if you are not sure of the special semantics of auto_ptr. (Edit: clarify based on Armen's comment)

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