lundi 19 mars 2018

Implicitly-declared move assignment operator

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

Aucun commentaire:

Enregistrer un commentaire