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:

#include 
#include 

class A {
  public:
    A(int x, int y){
      x_ = x;
      y_ = y;
    }
  private:
    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::move(tmp_a));

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

  // error
  std::unique_ptr 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::unique_ptr(const std::unique_ptr&)
      [with _Tp = A; _Dp = std::default_delete]’
   std::unique_ptr 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?

unique_ptr
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(vec_a.at(0));

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 = vec_a.at(0).get();

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

使用声明 | 英豪名录