Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why default move ctor and assignment are no more added by compiler when a destructor is defined?

I cannot understand the rationale behind the automatic addition of default ctors. In particular I find very awkward that every single time I just need to add an empty virtual destructor and nothing more, I loose the move stuffs, but adding them I loose the copy and default things, so I end up adding all this chunk of code:

virtual ~SomeClass(){}           // you are the guilty!
//virtual ~SomeClass() = default // would be the same

SomeClass(SomeClass&&) = default;                 // no more auto-added
SomeClass& operator=(SomeClass&&) = default;      // no more auto-added
SomeClass(const SomeClass&) = default;            // but with the moves defined,
SomeClass& operator=(const SomeClass&) = default; // I'm now missing the copy
SomeClass(){}                                     // and the default as well

I'm sure there is a reason for making my classes ugly and letting me desire an evil macro, I just would like to know it to feel more comfortable.

like image 870
DarioP Avatar asked Jul 24 '14 14:07

DarioP


1 Answers

Take a look at this. It explains something called the rule of five, which is essentially what standard requires.

Generally, for most cases, compiler creates defaults for copy constructor, copy assignment, move assignment, and destructor. But, if a programmer defines any of these, then the compiler assumes the user has encapsulated something in this class that requires his/her special, let's say. destructor. Now that the programmer knows that he/she is going to need a destructor, the compiler will know that the programmer know what's going on and just not create the defaults for the rest (because, based on the assumption that the compiler makes, the default ones are going to be wrong, and can even result in undesired behavior).

like image 195
triple_r Avatar answered Oct 14 '22 21:10

triple_r