1

In particular, if a class defines its own copy constructor, copy-assignment operator, or destructor, the move constructor and move-assignment operator are not synthesized.

—— quote from "13.6.2. Move Constructor and Move Assignment"

Why some compilers do not synthesize the move operations at all per this paragraph in C++ Primer 5th?

2
  • It's not "some" compilers, its all of them (at least those that attempt to be conforming).
    – Mat
    Sep 26, 2015 at 9:54
  • 1
    Because the standard says they shouldn't! ;) Those operations go together-if you define one, the automatically-generated ones almost certainly do the Wrong Thing.
    – cxw
    Sep 26, 2015 at 9:55

1 Answer 1

2

It is not just some compilers. Under the conditions listed in the quote, compilers are explicitly forbidden to synthesize the move operations.

Move operations were added quite recently to the C++ language, long after it had copy operations and destructors. And one thing that the maintainers of the C++ language standard try to maintain is that new features in the language do not break existing code, especially not if that code is part of the mainstream usage of the language.

If a class has its own copy constructor, copy-assignment operator and/or destructor, then in the large majority of cases those functions are doing some work that the compiler-synthesized version can't or won't do. If the compiler does synthesize move operations for such a class, then it is very likely that those move operations will not do the right thing.
For example, you have a class that maintains a database connection and has all the right copy operations and destructor to ensure that the connection would be closed at the right moment. If the compiler synthesized move operations for such a class, then the moved-from object would close the database connection, while the moved-to object is still using that connection.

There are all kinds of techniques to avoid such problems, but those are not always consistently used in legacy code and to avoid breaking that large body of code it was decided that move operations would not be silently added to classes where it might break the functioning of the class.
If you want move operations in a class that has its own copy constructor, copy-assignment operator or destructor, you have to write the move constructor and move-assignment operator yourself to ensure that they do the right thing.

0

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.