简体   繁体   中英

Passing a unique_ptr to a function which adds it to a vector

I have a class that holds a vector of 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:

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.

When I call addPointer , I also use 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.

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.

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).

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:

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));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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