为什么使用 std::auto_ptr<> 是错误的?使用标准容器? [英] Why is it wrong to use std::auto_ptr<> with standard containers?

查看:19
本文介绍了为什么使用 std::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.

这篇关于为什么使用 std::auto_ptr&lt;&gt; 是错误的?使用标准容器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆