I have a question about using std::move
in C++.
Let's say I have the following class, which in its constructor takes a std::vector
as a parameter:
class A
{
public:
A(std::vector<char> v): v(v) {}
private:
std::vector<char> v;
};
But if I write the following somewhere:
std::vector<char> v;
A a(v);
the copy constructor of std::vector
will be called twice, right?
So should I write constructor for A
like the following?
class A
{
public:
A(std::vector<char> v): v(std::move(v)) {}
private:
std::vector<char> v;
};
And what if I would like to call the following?
std::vector<char> v;
A a(std::move(v));
Is that okay with the second version of the constructor, or should I create another constructor for A
that takes std::vector<char>&&
?
Your second scheme is fine.
The vector will just be moved twice with the second version (which moves the by-value parameter into your member). If you don't mind the cost of the extra move, you can stick with just moving the by-value parameter into your member.
If you do mind, then make two constructors for different value categories of the parameter.