The basic version of my situation looks like this.
class MyClass
{
public:
MyClass(std::vector<int> v)
: m_vector(v) {}
void doSomething();
private:
std::vector<int> m_vector;
}
int main()
{
std::vector<int> myVector;
// ...
// Do stuff with myVector
// ...
MyClass myItem(myVector);
myItem.doSomething();
}
Obviously it is more efficient to move the vector into MyClass rather than copy it, but I am never sure how to define the constructor of MyClass and how to pass the argument when instantiating it.
The following versions all compile correctly.
A:
MyClass(const std::vector<int>& v)
: m_vector(std::move(v)) {}
MyClass myItem(myVector);
B:
MyClass(std::vector<int> v)
: m_vector(std::move(v)) {}
MyClass myItem(myVector);
C:
MyClass(const std::vector<int>& v)
: m_vector(v) {}
MyClass myItem(std::move(myVector));
D:
MyClass(const std::vector<int>& v)
: m_vector(std::move(v)) {}
MyClass myItem(std::move(myVector));
E:
MyClass(std::vector<int>&& v)
: m_vector(std::move(v)) {}
MyClass myItem(std::move(myVector));
…and I’m just getting more confused. I guess the question is not even which one is “correct”, but which one guarantees the least copies?
4