Error after trying to get the unique_ptr element of the vector

I read about how to insert a unique_ptr
into a vector<unique_ptr>
: Why can I not push_back a unique_ptr into a vector?

But how do I get a element back? I made an example:


class A {
    A(int x, int y){
      x_ = x;
      y_ = y;
    int x_;
    int y_;

int main(){
  std::vector<std::unique_ptr> vec_a;
  std::unique_ptr tmp_a = std::unique_ptr(new A(13,32));


  vec_a.push_back(std::unique_ptr(new A(3,2)));

  // error
  std::unique_ptr a =;

I’m getting this error message: In function ‘int main()’: error: use of deleted function
      ‘std::unique_ptr::unique_ptr(const std::unique_ptr&)
      [with _Tp = A; _Dp = std::default_delete]’
   std::unique_ptr a =;
In file included from /usr/include/c++/4.8/memory:81:0,
/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?

cannot be copied or assigned. It needs to be move
copied or move
assigned. You can achieve this by use of std::move

std::unique_ptr a = std::move(;

The call to std::move
essentially allows you to treat the RHS as an rvalue, which can then be used in unique_ptr
‘a move copy constructor.

Note that after this, you will have to be careful with the first element of vec_a

If you don’t want to take ownership of the pointer away from the vector, simply access the managed pointer directly:

A* a =;

You have to be careful not to use a
after the object it points to has ceased to exist.

Hello, buddy!责编内容来自:Hello, buddy! (源链) | 更多关于

本站遵循[CC BY-NC-SA 4.0]。如您有版权、意见投诉等问题,请通过eMail联系我们处理。
酷辣虫 » 综合编程 » Error after trying to get the unique&lowbar;ptr element of the vector

喜欢 (0)or分享给?

专业 x 专注 x 聚合 x 分享 CC BY-NC-SA 4.0

使用声明 | 英豪名录