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

时间:2010-10-19 19:11:14

标签: c++ auto-ptr

std :: auto_ptr缺少const拷贝构造函数,因此我不能直接在集合中使用它。有没有办法在不使用boost指针集合模板的情况下拥有std :: auto_ptr的矢量?

3 个答案:

答案 0 :(得分:3)

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

@James McNellis提供了一个正确的unique_ptr使用here礼貌的好例子。对于shared_ptr演练here,由@ D.Shawley提供。 [我确信,在这些主题上仍然会赞赏Upvotes。]

虽然Visual C ++ v6不同意,但vector的{​​{1}}始终无效。

答案 1 :(得分:2)

不,你不能拥有std::auto_ptr的向量,尽管你可以做很多猜测。但是如果你的编译器支持C ++ 0x,你可以使用std::unique_ptr,它是不推荐使用的自动指针的新选择,引用新标准提供了一个更好的选择。另请参阅this thread

答案 2 :(得分:1)

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的特殊语义,那么超出此用途的任何内容都可能存在危险和/或损坏。 (编辑:根据Armen的评论澄清)

相关问题