I read about how to insert a unique_ptr<T>
into a vector<unique_ptr<T>>
: Why can I not push_back a unique_ptr into a vector?
But how do I get a element back? I made an example:
#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);
}
I'm getting this error message:
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;
^
What I'm doing wrong? How should I do it? And why does this not work?