Why would you need a move constructor when unnamed objects only are alive until the end of the full-expressions anyway? If we had this code:
class Example6 {
string* ptr;
public:
Example6 (const string& str) : ptr(new string(str)) {}
~Example6 () {delete ptr;}
// move constructor
Example6 (Example6&& x) : ptr(x.ptr) {x.ptr=nullptr;}
// move assignment
Example6& operator= (Example6&& x) {
delete ptr;
ptr = x.ptr;
x.ptr=nullptr;
return *this;
}
};
int main () {
Example6 bar = Example6("ple"); // move-construction
return 0;
}
We have an Rvalue reference as the parameter for the move constructor and assignment operation. In this case, bar
's move constructor is called when it is initialized to a temporary of the same class. The thing that I do not understand is: Since temporaries have the lifetime of the full-expression, why is there a need for a move constructor instead of a copy constructor? I mean, implicit defined move constructor and assignment operator "erase" the data from the temporary, even though this data would all be destroyed after the semicolon, so why do you need a move constructor, which somewhat does the same as copy constructor... Why is there a need to erase data from a temporary that gets destroyed after the semicolon anyway?