skip to content

In C++, why does a class with a reference data member lose its copy assignment operator?

level: middleimportance: should knowfreq 52%

answer

  1. references cannot be reseated
  2. defaulted assignment defined as deleted
  3. copy construction still works
  4. std::sort and erase need assignment

basics

~20 s

Assignment would have to reseat the reference, which the language cannot do, so the implicitly declared copy and move assignment operators are defined as deleted. Copy construction still works; store a pointer or std::reference_wrapper to regain assignment.

solid answer

~40 s

The standard says a defaulted copy or move assignment operator is defined as deleted if the class has a non-static data member of reference type (or of const non-class type). Member-wise assignment of `const Point& at` would mean either reseating the reference - impossible - or writing through it into someone else's object, which would be a surprise, so the language refuses. Clang reports `copy assignment operator of 'Anchor' is implicitly deleted because field 'at' is of reference type`. Copy construction is unaffected, so `std::vector<Anchor>::push_back` works, but `std::sort`, `std::vector::erase` and `std::swap` need assignment and fail. The member must also be bound in every constructor's member initializer list. Use `std::reference_wrapper<const Point>` or `const Point*` when the class must stay assignable.

code

cpp · 29 lines
cpp
#include <algorithm>
#include <cstdio>
#include <functional>
#include <vector>

struct Point { double x, y; };

struct Anchor {                           // a label pinned to a point owned elsewhere
    const Point& at;                      // reference member
    int id;
};

struct AnchorW {                          // same idea, but assignable
    std::reference_wrapper<const Point> at;
    int id;
};

int main() {
    Point p{1, 2}, q{5, 6};
    Anchor a{p, 1};
    Anchor copy = a;                      // copy construction works: copy.at refers to p
    // a = copy;  // error: copy assignment operator is implicitly deleted because
    //            //        field 'at' is of reference type 'const Point &'

    std::vector<AnchorW> labels{{q, 2}, {p, 1}};
    std::sort(labels.begin(), labels.end(),          // needs assignment: fine here
              [](const AnchorW& l, const AnchorW& r) { return l.id < r.id; });
    std::printf("%.0f %.0f\n", copy.at.x, labels.front().at.get().x);
}

go deeper

for a junior

Recall that a reference member must be bound in the member initializer list and that it stops the class from being assigned, though it can still be copied.

for a middle

Explain the deleted-defaulted-assignment rule, why construction still works, and which containers and algorithms then fail because they need assignment.

for a senior

Read the library-deep error from std::sort back to its cause, and choose between reference_wrapper, a pointer or keeping the reference by the class's role.

for a principal

Set a rule for value types stored in containers to avoid reference members, reserving them for short-lived views and function objects.

## The rule When you do not declare a copy assignment operator, the compiler declares one for you that assigns member by member. The standard then lists cases where that defaulted operator is **defined as deleted**. A class has a deleted defaulted copy/move assignment operator if it has: - a non-static data member of **reference type**, or - a non-static data member of `const` non-class type, or - a member or base whose own assignment is inaccessible, deleted or ambiguous. The reasoning for references follows from the previous lessons: a reference is bound once and assignment through it writes to the referent. A member-wise `this->at = other.at;` would therefore copy one `Point` into another `Point` that neither label owns, while leaving both labels attached where they were. Neither "reseat" nor "write through" is a sensible meaning, so the language gives none. ## What still works and what breaks ```cpp struct Anchor { const Point& at; // a label pinned to a point owned elsewhere int id; }; ``` | Operation | Works? | Why | |---|---|---| | `Anchor a{p, 1};` | yes | aggregate initialization binds the reference | | `Anchor copy = a;` | yes | copy **construction** binds a new reference to the same `Point` | | `copy = a;` | no | deleted copy assignment | | `std::vector<Anchor>::push_back` | yes | needs only construction | | `std::vector<Anchor>::erase` / `insert` in the middle | no | shifts elements by assignment | | `std::sort`, `std::swap` | no | both assign | | `std::optional<Anchor>::operator=` | no | its assignment needs the contained type's assignment | Clang's error for `std::sort` points deep into the library - `sift_down.h` in libc++ - with "object of type 'Anchor' cannot be assigned because its copy assignment operator is implicitly deleted". Recognizing that message is a practical skill. The implicitly declared **move** assignment is also defined as deleted, and a defaulted move assignment defined as deleted is ignored by overload resolution, so an rvalue falls back to the deleted copy assignment - which is why the diagnostic talks about copy assignment even when the code moves. ## Constructors must bind the member Because a reference cannot be left unbound, every constructor must initialize it in the **member initializer list** (or via aggregate initialization): ```cpp class Anchor { public: Anchor(const Point& at, int id) : at_(at), id_(id) {} // binding happens here private: const Point& at_; int id_; }; ``` Assigning `at_ = at;` in the constructor body is not binding: a constructor that omits `at_` from its initializer list is rejected with "constructor for 'Anchor' must explicitly initialize the reference member 'at_'". For a class without user-declared constructors, the defaulted default constructor is defined as deleted, since nothing would bind the reference. ## The alternatives 1. **`std::reference_wrapper<const Point>`** - a copy-assignable wrapper around a reference. Assigning one wrapper to another rebinds it, `get()` returns the `const Point&`, and the class keeps all its special members. This is the closest drop-in replacement. 2. **`const Point*`** - a plain pointer member: assignable, but nullable, so the class must document or check that it is never null. 3. **Keep the reference** - when the object is meant to be a short-lived, non-assignable view (a visitor, a scope guard, a function object that lives for one call), a reference member is a clear statement that the binding never changes. ## Lifetime is still yours Whichever spelling you choose, the class refers to an object it does not own. If the `Point` is destroyed first, every `Anchor` dangles; dangling references as a bug class are covered with dangling and use-after-free. A reference member makes the non-owning relationship visible in the type, which is exactly why reviewers flag one in a class that is stored in containers. ## Interview checklist - Name the rule: defaulted assignment is deleted because of the reference member. - Distinguish construction (fine) from assignment (deleted). - List which containers and algorithms need assignment. - Offer `std::reference_wrapper` or a pointer, and say when keeping the reference is the better design.

  • Could you write a user-defined operator= for a class with a reference member?
    Yes, but it can only copy the other members or write through the reference into the referred object; it still cannot reseat it. Either meaning surprises callers, which is why the defaulted one is deleted. If a class needs assignment that changes what it refers to, it should hold a `std::reference_wrapper` or a pointer instead.
  • Does a const int data member cause the same problem?
    Yes. The same rule deletes the defaulted copy and move assignment for a non-static data member of const non-class type, because assigning would modify a const object. The class stays copy-constructible but not assignable, so it fails in `std::sort` and `vector::erase` the same way. A const member of class type depends on that class's own assignment operator.

  • A reference member makes the class non-copyable
  • Assignment rebinds the reference member to the other object's referent
  • A reference member can be bound in the constructor body
  • std::vector cannot hold a class with a reference member at all
  • Adding a move assignment operator = default fixes the reference member problem