obmarg
obmarg

Reputation: 9559

Will C++ use a move constructor from a copy assignment operator?

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?

Upvotes: 1

Views: 482

Answers (2)

Nicol Bolas
Nicol Bolas

Reputation: 473262

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::move or a similar cast (such as std::forward in 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.

Or will I need to explicitly define a move constructor/assignment operator for SimpleStruct to take advantage of a vector 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.

Upvotes: 3

Potatoswatter
Potatoswatter

Reputation: 137770

Inside a copy constructor or copy assignment operator, copy means copy. The language never makes any contextual adjustment to the contents of a function based on how it is called.

However, it's likely that no copy will occur in SimpleStruct value = GetStruct(); because copy elision applies.

Upvotes: 1

Related Questions