C++11 – Why Synthesized Copy-Assignment Operator is Deleted with Reference Member

c++c++11

In C++ Primer, Fifth Edition, ยง13.1.6:

The synthesized copy-assignment operator is defined as deleted if a member has a deleted or inaccessible copy-assignment operator, or if the class has a const or reference member.

The explanation from the chapter:

Although we can assign a new value to a reference, doing so changes the value of the object to which the reference refers. If the copy-assignment operator were synthesized for such classes, the left-hand operand would continue to refer to the same object as it did before the assignment. It would not refer to the same object as the right-hand operand. Because this behavior is unlikely to be desired, the synthesized copy-assignment operator is defined as deleted if the class has a reference member.

Copying the class changes the object to which the reference member refers. Isn't this desired? Why the explanation say "is unlikely to be desired"?

Concretely,

class A {
public:
    A(int &n) : a(n) {}
private:
    int &a;
};

int main() {
    int n = 1;

    A a(n);

    /* Why is this allowed? */
    A b(a);

    /*
    Why is this not allowed?
    error C2280: 'A &A::operator =(const A &)': attempting to reference a deleted function
    */
    b = a;

    return 0;
}

Best Answer

A reference can't be reassigned once it's created. That means it's impossible to make a proper assignment operator if the class contains a reference member.

A copy constructor is a different matter, because the reference can be assigned at object creation.

Related Question