std::auto_ptr缺少const复制构造函数,因此我不能直接在集合中使用它。是否有一些方法可以使用std :: auto_ptr的vector,而不使用boost指针集合模板?
不,你不能拥有一个 std::auto_ptr
的向量,尽管存在许多可以这样做的猜测。但是如果你的编译器支持 C++0x,你可以使用 std::unique_ptr
,它是被弃用的自动指针的新替代品,引用新标准中的话说,提供了更好的替代方案。另请参见此线程
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的评论进行澄清)
shared_ptr
不需要 C++0x,它在 TR1 中。 - Potatoswatterunique_ptr
更适合纠正有缺陷的auto_ptr
语义。 - Steve Townsend