Home > Net >  How does copy constructor that returns value, discards the temp?
How does copy constructor that returns value, discards the temp?

Time:11-22

having this code:

#include <iostream>

class Base {
public:
    Base() = default;

    explicit Base(int val) : _var(val) {}

    Base operator=(const Base &rhs) {
        _var = rhs._var;
        return *this;
    }

    void print() const {
        std::cout << _var << std::endl;
    }

private:
    int _var;
};

int main() {
    Base b[] = {Base(10), Base(), Base(), Base()};
    (b[1] = b[2]) = b[0];
    for (Base base: b) {
        base.print();
    }
}

the output is:

10
0
0
0

but I would expect

10
10
0
0

As the second element in array b[1] should get assign from b[0], but the assignment operator returns value, not reference and thus copy-constructing happen. But still, why is not b[1] copy-constructed to have _var=10?

If the operator= returned Base &, the output would be my expectation

CodePudding user response:

To get the desired result of your assignment operator (which, by the way, is different from copy constructor), you need to return a reference:

Base& operator=(const Base &rhs)

This is the canonical form.

Without the reference, the result of (b[1] = b[2]) is stored in a temporary. (b[1] = b[2]) = b[0]; assigns to that temporary, which is discarded and has no effect on b[1].

  • Related