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

user3613174
  • 669
  • 1
  • 7
  • 13
  • 1
    It is often a misconception to think that `std::move` moves the object. Refer to [What is std::move, and when should it be used](https://stackoverflow.com/questions/3413470/what-is-stdmove-and-when-should-it-be-used). – Mário Feroldi Mar 19 '18 at 14:29

1 Answers1

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

Vittorio Romeo
  • 90,666
  • 33
  • 258
  • 416