简体   繁体   English

将unique_ptr传递给将其添加到向量的函数

[英]Passing a unique_ptr to a function which adds it to a vector

I have a class that holds a vector of unique_ptr. 我有一个类,包含一个unique_ptr向量。 The class also has a method to add an element to the vector. 该类还有一个向向量添加元素的方法。

class PointerVector
{
  public:
    void addPointer(std::unique_ptr<int> p);

  private:
    std::vector<std::unique_ptr<int>> mPointers;
};

The addPointer method definition: addPointer方法定义:

void PointerVector::addPointer(std::unique_ptr<int> p)
{
  mPointers.emplace_back(std::move(p));
}

So I use std::move to transfer ownership of the pointer. 所以我使用std::move来转移指针的所有权。

When I call addPointer , I also use std::move : 当我调用addPointer ,我也使用std::move

PointerVector pv;
std::unique_ptr<int> i(new i(1));
pv.addPointer(std::move(i));

Is this the correct way to do things? 这是正确的做事方式吗? It feels like a hassle having to call std::move all the time. 感觉好像一直在打电话给std::move很麻烦。

Edit : I actually want to hold a vector of unique_ptr to a class, but I wanted to try with an int first, to make things easier. 编辑 :我实际上想要将unique_ptr的向量保存到类中,但我想先尝试使用int,以使事情变得更容易。

Almost. 几乎。 You don't need to use std::move() when passing a temporary, your last fragment would look better as below (I am not asking why you need to store a smart pointer to an int rather than an int itself). 传递临时数据时,您不需要使用std::move() ,最后一个片段看起来会更好,如下所示(我不是在问为什么您需要存储指向int而不是int本身的智能指针)。

PointerVector pv;
pv.addPointer(std::unique_ptr<int>(new int(1)));

Since you're using emplace_back to construct a new unique_ptr<int> element directly in the right place at the end of your vector, maybe the simplest solution is to let your PointerVector class encapsulate the whole unique_ptr management logic and just give it a raw pointer: 由于你正在使用emplace_back直接在向量的末尾构造一个新的unique_ptr<int>元素,也许最简单的解决方案是让你的PointerVector类封装整个unique_ptr管理逻辑并给它一个原始指针:

class PointerVector
{
  public:
    void addPointer(int* p);

  private:
    std::vector<std::unique_ptr<int>> mPointers;
};


void PointerVector::addPointer(int* p) {
     assert(nullptr != p);
     mPointers.emplace_back(p);
}

PointerVector pv;
pv.addPointer(new int(1));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM