0

I'm having trouble getting my head around this simple rule from cpp reference;

If no user-defined move assignment operators are provided for a class type (struct, class, or union), and all of the following is true:

there are no user-declared copy constructors;

there are no user-declared move constructors;

there are no user-declared copy assignment operators;

there are no user-declared destructors;

the implicitly-declared move assignment operator would not be defined as deleted, (until C++14)

THEN the compiler WILL declare a move assignment operator as an inline public member of its class with the signature T& T::operator=(T&&).

With this in mind, consider

struct bar
{

   bar(int i) : _i(i) {};
   bar (const bar& other) { };
   bar (bar& other) { };

   int _i;
};

Followed by this, say;

   bar b2(2);
   bar b3(3);
   cout << "b3._i " << b3._i << endl << endl;
   b3 = std::move(b2);
   cout << "b3._i " << b3._i << endl;

The output we get is;

b3._i 3

b3._i 2

So here we have a move happening;

b3 = std::move(b2);

I didn't define that move assignment operator, so its been implicitly defined for me by the compiler. However I have broken the conditions laid down, I HAVE a user defined copy ctor.... however there is still a move happening by the compiler generated one. I'm clearly misinterpreting the text, can anybody be so good as to enlighten me?

Thanks and have a nice day.

G

1

1 Answer 1

3

So here we have a move happening;

b3 = std::move(b2);

Nope, this is a copy. std::move(b2) simply casts b2 to bar&&. bar&& then binds to const bar& in the implicitly-generated copy-assignment operator.

live example on wandbox

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.