Move assignment called instead of normal assignment operator

I've got the following code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
#include <iostream>

using namespace std;

class Matris {
public:
    Matris() {
    
    }
    
    Matris(const Matris& m) {
        
    }
    
    ~Matris() {
        cout<<"Destructor\n";
    }
    
    void operator=(const Matris& m2) {
        cout<<"Normal assignment\n";
    }
    
    void operator=(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.
Last edited on
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.
Last edited on
Topic archived. No new replies allowed.