3

I am trying to learn about move constructors. I wrote the below program.

#include <iostream> #include <algorithm> using namespace std; class myclass { public: myclass() { cout << "In Constructor" << endl; } ~myclass() { cout << "In Destructor" << endl; } myclass(const myclass &obj) { cout << "In Copy Constructor" << endl; } myclass(myclass &&obj) { cout << "In Move Constructor" << endl; } }; int main() { myclass obj = myclass(); // Line 1 myclass obj(myclass()); // Line 2 } 

Line 1 is working as expected, move constructor is getting called if I use '-fno-elide-constructors' flag. But for line 2, nothing is happening. Not even constructor is getting called. I thought that move constructor will be called for line 2 also. But no function is getting called. I know if I call the constructor explicitly, the object will be destroyed at the end of the expression. But I am not sure why even constructor is not getting called. Can any one please let me know what is wrong with Line 2?

1 Answer 1

8

This is an example of the most vexing parse; obj is declared to be a function, rather than an object of type myclass. Most instances of the most vexing parse can be avoided by changing one (or both) pairs of parentheses to braces. For example:

myclass obj(myclass{}); 

Note that even in C++11, the compiler may optimize out the move (with both direct-initialization and copy-initialization). In C++17, the move is guaranteed to not occur; the object will simply be value-initialized.

Sign up to request clarification or add additional context in comments.

1 Comment

FYI: please enable the compiler warning for this! (And promote it to error), you really never need it to become function declaration

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.