我读到了如何插入unique_ptr< T>到矢量< unique_ptr< T>>:
Why can I not push_back a unique_ptr into a vector?
但是我如何获得一个元素呢?我做了一个例子:
#include <memory> #include <vector> class A { public: A(int x,int y){ x_ = x; y_ = y; } private: int x_; int y_; }; int main(){ std::vector<std::unique_ptr<A>> vec_a; std::unique_ptr<A> tmp_a = std::unique_ptr<A>(new A(13,32)); vec_a.push_back(std::move(tmp_a)); vec_a.push_back(std::unique_ptr<A>(new A(3,2))); // error std::unique_ptr<A> a = vec_a.at(0); }
我收到此错误消息:
main.cc: In function ‘int main()’: main.cc:24:36: error: use of deleted function ‘std::unique_ptr<_Tp,_Dp>::unique_ptr(const std::unique_ptr<_Tp,_Dp>&) [with _Tp = A; _Dp = std::default_delete<A>]’ std::unique_ptr<A> a = vec_a.at(0); ^ In file included from /usr/include/c++/4.8/memory:81:0,from main.cc:1: /usr/include/c++/4.8/bits/unique_ptr.h:273:7: error: declared here unique_ptr(const unique_ptr&) = delete; ^
我做错了什么?我该怎么办?为什么这不起作用?