为什么在标准容器中使用std::auto_ptr<>是错误的?

最佳答案

C++标准指出,STL元素必须是“可复制构造的”和“可分配的”。换句话说,必须能够分配或复制一个元素,并且这两个元素在逻辑上是独立的。 std::auto_ptr不满足此要求。

以下面的代码为例:

class X
{
};

std::vector<std::auto_ptr<X> > vecX;
vecX.push_back(new X);

std::auto_ptr<X> pX = vecX[0];  // vecX[0] is assigned NULL.

要克服此限制,如果没有C++ 11,则应使用 std::unique_ptr std::shared_ptr std::weak_ptr 智能指针或boost等价物。 Here is the boost library documentation for these smart pointers.

关于c++ - 为什么在标准容器中使用std::auto_ptr <>是错误的?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/111478/

10-11 22:52
查看更多