Reputation: 5376
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?
Upvotes: 3
Views: 84
Reputation: 119174
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.
Upvotes: 8