mardi 3 octobre 2017

Is it good to use a unique pointer to a vector as a function parameter?

One of my function takes a vector as a parameter and stores it as a member variable. I am using const reference to a vector as described below.

class Test {
 public:
  void someFunction(const std::vector<string>& items) {
   m_items = items;
  }

 private:
  std::vector<string> m_items;
};

However, sometimes items contains a large number of strings, so I'd like to add a function (or replace the function with a new one) that supports move semantics. I am thinking of several approaches, but not sure which one is the most preferred way.

1) unique_ptr

void someFunction(std::unique_ptr<std::vector<string>> items) {
   // Also, make `m_itmes` std::unique_ptr<std::vector<string>>
   m_items = std::move(items);
}

2) pass by value and move

void someFunction(std::vector<string> items) {
   m_items = std::move(items);
}

3) rvalue

void someFunction(std::vector<string>&& items) {
   m_items = std::move(items);
}

Which approach should I avoid and why?

Aucun commentaire:

Enregistrer un commentaire