Why is it wrong to use std::auto_ptrlt;gt; with standard containers?(为什么使用 std::auto_ptrlt;gt; 是错误的?使用标准容器?)
问题描述
为什么在标准容器中使用 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<> 是错误的?使用标准容器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:为什么使用 std::auto_ptr<> 是错误的?使用标准容器?


基础教程推荐
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 常量变量在标题中不起作用 2021-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 这个宏可以转换成函数吗? 2022-01-01
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 我有静态或动态 boost 库吗? 2021-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09