问题描述
为什么在标准容器中使用 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<> 是错误的?使用标准容器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!


大气响应式网络建站服务公司织梦模板
高端大气html5设计公司网站源码
织梦dede网页模板下载素材销售下载站平台(带会员中心带筛选)
财税代理公司注册代理记账网站织梦模板(带手机端)
成人高考自考在职研究生教育机构网站源码(带手机端)
高端HTML5响应式企业集团通用类网站织梦模板(自适应手机端)