Reputation: 793
I'm reading a chapter in c++ priemr about copy construct,the book says “During copy initialization, the compiler is permitted (but not obligated) to skip the copy/move constructor and create the object directly. That is, the compiler is permitted to rewrite
string null_book="xxxxxxx";
into
string null_book("xxxxxxx");
even if the compiler omits the call to the copy/move constructor, the copy/move constructor must exist and must be accessible"
then i write a class and delete copy constructor
class myclass {
public:
myclass(int a):id(a){
std::cout << "construct: "<<id<<std::endl;
}
myclass(const myclass& s) = delete;
myclass& operator=(const myclass& s) = delete;
private:
int id=0 ;
};
if i do this it compiled successfully
myclass c = 2;
but this gives me error
myclass c =myclass(2);
i'm totally confused, please help me,thanks a alot
Upvotes: 1
Views: 592
Reputation: 238341
myclass c = expr;
is copy initialisation. Before C++17, for this to be well-formed, the type must be copyable or at least movable.
Since C++17, the expression that is used to initialise the temporary (in first case, there is implicit conversion from int that produces the temporary) is used to initialise c
instead, so there is no copy/move involved and the program is well-formed in the latest standard.
Upvotes: 1
Reputation: 1202
Move constructor is required.
C++ compiler must do RVO(Return Value Optimization) so that move constructor is now not required.
P0135R1 Wording for guaranteed copy elision through simplified value categories
Upvotes: 1