Unless you have a reason for the vector to live on the heap, I would advise against using unique_ptr
The vector's internal storage lives on the heap anyway, so you'll be requiring 2 degrees of indirection if you use unique_ptr
, one to dereference the pointer to the vector, and again to dereference the internal storage buffer.
As such, I would advise to use either 2 or 3.
If you go with option 3 (requiring an rvalue reference), you are foisting a requirement on the users of your class that they pass an rvalue (either directly from a temporary, or move from an lvalue), when calling someFunction
.
The requirement of moving from an lvalue is onerous.
If your users want to keep a copy of the vector, they have to jump through hoops to do so.
std::vector<string> items = { "1", "2", "3" };
Test t;
std::vector<string> copy = items; // have to copy first
t.someFunction(std::move(items));
However, if you go with option 2, the user can decide if they want to keep a copy, or not - the choice is theirs
Keep a copy:
std::vector<string> items = { "1", "2", "3" };
Test t;
t.someFunction(items); // pass items directly - we keep a copy
Don't keep a copy:
std::vector<string> items = { "1", "2", "3" };
Test t;
t.someFunction(std::move(items)); // move items - we don't keep a copy
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…