Seeing as C++11 supports move semantics, when initializing data members from arguments, should we attempt to move the value instead of copying it?
Here’s an example showing how I would approach this in pre-C++11:
struct foo {
std::vector<int> data;
explicit foo(const std::vector<int>& data)
: data(data)
{
}
};
Here, the copy constructor would be called.
In C++11, should we get into the habit of writing like this:
struct foo {
std::vector<int> data;
explicit foo(std::vector<int> data)
: data(std::move(data))
{
}
};
Here, the move constructor would be called… as well as the copy constructor if the argument passed is an lvalue, but the benefit is that if an rvalue was passed, the move constructor would be called instead of the copy one.
I’m wondering if there’s something I’m missing.
My initial answer to your question was:
Don’t copy data that you want to move. You can add a constructor using a rvalue reference, if performance is a problem:
Not exactly matching your question, but reading
Rule-of-Three becomes Rule-of-Five with C++11?
seems to be useful.
Edit:
However, the accepted answer to
Passing/Moving parameters of a constructor in C++0x
seems to advocate your approach, especially with more than one parameter.
Otherwise there would be a combinatorial explosion of variants.