#include <iostream>
usingnamespace std;
class Matris {
public:
Matris() {
}
Matris(const Matris& m) {
}
~Matris() {
cout<<"Destructor\n";
}
voidoperator=(const Matris& m2) {
cout<<"Normal assignment\n";
}
voidoperator=(Matris&& m2) {
cout<<"Move assignment\n";
}
Matris operator+(Matris& m2) {
return Matris();
}
};
int main () {
Matris x;
x = x + x;
return 0;
}
The output is:
1 2 3
Move assignment
Destructor
Destructor
I have two questions:
1. Why is the copy constructor for a class called when a function returns an object instance of that class?
2. Why is the move assignment operator function called instead of the normal assignment operator function? Shouldn't the temporary object created by (x + x) be deleted even if the normal assignment operator is chosen? If I remove my definition of the move assignment operator function, the compiler chooses my desired normal assignment operator function instead. I use Xcode.
1. Why is the copy constructor for a class called when a function returns an object instance of that class?
In most cases it isn't: both copy elision and move are given preference over copy when returning by value. Give an example if there's a specific case you're asking about.
2. Why is the move assignment operator function called instead of the normal assignment operator function?
The expression x + x is an rvalue expression of type Matris (because it's a function call to a value-returning function). Given an rvalue argument, overload resolution between operator=(const Matris&) (copy-assignment) and operator=(Matrix&&) (move-assignment) selects move-assignment. Because that's exactly what it's for.
Shouldn't the temporary object created by (x + x) be deleted even if the normal assignment operator is chosen?
Like any temporary object, it is deleted at the semicolon. That's your first "Destructor" line. Assignment has nothing to do with it.
If I remove my definition of the move assignment operator function
then overload resolution has only one thing to consider: the copy-assignment operator, you gave it no other choice.