为什么使用std :: auto_ptr<>与标准集装箱? [英] Why is it wrong to use std::auto_ptr<> with standard containers?

查看:162
本文介绍了为什么使用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_ptr std :: 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天全站免登陆