Why is the move constructor involved here

  • A+

I have this piece of C++ code:

class Args {};  class MyClass {   public:   MyClass(Args& a) {}   MyClass(MyClass &&) = delete; };  int main() {    Args a;   MyClass c1 = MyClass(a);   MyClass c2 = a;   MyClass c3(a);    return 0; } 

This does not compile because the construction of objects c1 and c2 seem to involve the class's move constructor:

error: use of deleted function ‘MyClass::MyClass(MyClass&&)’

It seems as if the compiler wants to create temporary object and then move them to c1 and c2. Why is this happening? Shouldn't all three statements just call the MyClass(Args& a) constructor?

On the other hand, if I do create the move constructor the program compiles fine and the move constructor is never called!!!


See copy elision:

Under the following circumstances, the compilers are permitted, but not required to omit the copy- and move- (since C++11) construction of class objects even if the copy/move (since C++11) constructor and the destructor have observable side-effects. This is an optimization: even when it takes place and the copy-/move-constructor is not called, it still must be present and accessible (as if no optimization happened at all), otherwise the program is ill-formed.

Since C++17:

They need not be present or accessible, as the language rules ensure that no copy/move operation takes place, even conceptually.


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: