据我所知,auto_ptr不能与矢量一起使用,因为auto_ptr不符合作为可复制构造的要求。由于被复制的auto_ptr被修改,因此复制不会导致两个完全相同的副本,从而违反了可复制构造方式。为什么unique_ptr可以用于std容器,vector <>例如?
Unique_ptr也似乎也这样做;它修改被复制的对象 - 被复制对象的指针成员被设置为nullptr。 那么,怎么可能使用uinque_ptr与矢量而不是auto_ptrs?
我的理解是否正确或我在这里错过了什么?
auto_ptr <int> autoPtr(new int);
vector < auto_ptr <int> > autoVec;
autoVec.push_back(autoPtr); //compiler error..why?
unique_ptr <int> uniquePtr(new int);
vector < unique_ptr <int> > uniqueVec;
uniqueVec.push_back(std::move(uniquePtr)); //okay..why?
[所以你不能复制它](http://coliru.stacked-crooked.com/a/495f091f798712ab),[但你可以移动它](http://coliru.stacked-crooked.com/ a/361fc294fb13279d) – 2015-02-24 05:01:16
@VxxGxx这只是'auto_ptr'不能提供任何防止被尝试复制清除的保护。此外,'auto_ptr'已弃用。不过,这至少会给你一个警告。 – 2015-02-24 06:34:03
@BryanChen我们可以拷贝(通过auto_ptr中的非const引用)或者移动它(通过右值引用),被拷贝的对象被改变。这违反了复制构造的习惯用法。那么是什么让unique_ptr适合像vector这样的容器而不是auto_ptr? – Vishal 2015-02-24 08:18:35