Say I have a simple struct that contains a vector and defines a copy assignment operator, and a function that returns this struct, like so:
struct SimpleStruct
{
vector< int > vec1;
operator=( SimpleStruct& other )
{
vec1 = other.vec1;
}
}
SimpleStruct GetStruct();
As I understand it, because I’ve declared a copy assignment operator, the compiler won’t automatically generate a move constructor for SimpleStruct.
So if I use the GetStruct function like this:
SimpleStruct value = GetStruct();
Is the compiler smart enough to move rather than copy the vector when I say vec1 = other.vec1;? Or will I need to explicitly define a move constructor/assignment operator for SimpleStruct to take advantage of a vector move?
C++11 has very strict rules about when movement is allowed to happen. And unless a temporary is involved, those rules require the explicit use of
std::moveor a similar cast (such asstd::forwardin some cases).Yes, you could move something. But it wouldn’t happen by accident; it would have to be deliberate.
Also, it is generally rude to write a copy-assignment operator that can modify what is being copied. That’s why they usually take a
const&, which pretty much guarantees the inability to move.In general, this is why you don’t explicitly define copy and move constructors. Let the compiler do it’s job and generate those for you (unless you’re using VC++ which doesn’t do its job for move constructors/assignment). Only explicitly write copy/move constructors for lower-level containers; anything larger should just rely on those value types to do their jobs.