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

2022-01-07 00:00:00 c++ stl c++-faq raii auto-ptr

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

Why is it wrong to use std::auto_ptr<> with standard containers?

推荐答案

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

The C++ Standard says that an STL element must be "copy-constructible" and "assignable." In other words, an element must be able to be assigned or copied and the two elements are logically independent. std::auto_ptr does not fulfill this requirement.

以这段代码为例:

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.

要克服此限制,您应该使用 std::unique_ptr, std::shared_ptrstd::weak_ptr 智能指针或 boost 等价物,如果您没有 C++11.这里是这些智能指针的 boost 库文档.

To overcome this limitation, you should use the std::unique_ptr, std::shared_ptr or std::weak_ptr smart pointers or the boost equivalents if you don't have C++11. Here is the boost library documentation for these smart pointers.

相关文章