Copy/move assignment operators
Which operator= functions are copy or move assignment operators, when the compiler implicitly declares or deletes them (const members, reference members), why a derived class always hides the base class operator=, and the implicitly-defined memberwise assignment.
Key points
- A copy assignment operator is a non-template
operator=with exactly one non-object parameter of typeXorcv X&; with acv X&¶meter it is a move assignment operator. Unlike constructors, a by-value parameterXis allowed. - The move assignment operator has the same strict conditions for implicit declaration as the move constructor: if the user declares any of the copy constructor, move constructor, copy assignment or destructor, it doesn't exist, and rvalue assignment uses copy assignment instead.
- For a class with a
constscalar member or a reference member, the defaulted assignment operators are deleted, because a reference can't be rebound and a const member can't be modified. - A derived class always has its own
operator=(implicit or explicit), so all the base class'soperator=overloads are hidden; bring them in with a using-declaration. - The implicitly-defined assignment operator assigns the direct bases, then the members, in declaration order, and returns
*this; a virtual base may be assigned more than once.
The difference between assignment and construction is that construction turns a piece of storage into an object, while assignment replaces the value of an object that already exists. So a hand-written assignment operator has to deal with the old value: release the old resources, cope with self-assignment, and stay exception safe. This subclause is structured in parallel with [class.copy.ctor].
Which operator= functions are copy/move assignment operators (¶1, ¶3)#
struct X {
X();
X& operator=(X&); // copy assignment operator
};
const X cx;
X x;
void f() {
x = cx; // error: X& can't bind to a const X
}¶1 A copy assignment operator of class X is a non-static non-template member function X::operator= with exactly one non-object parameter of type X, X&, const X&, volatile X& or const volatile X&.
¶3 A move assignment operator is defined the same way, except that the parameter type is X&&, const X&&, volatile X&& or const volatile X&&.
Compared with the copy constructor, there are two differences:
- A by-value parameter
Xis allowed.X& operator=(X other)is a copy assignment operator; this is how the copy-and-swap idiom is written (see below). A constructor can't be written this way ([class.copy.ctor]/5), because taking the argument by value would first require copy construction; an assignment operator has no such recursion. - Only non-object parameters count. Since C++23 an assignment operator can have an explicit object parameter (P0847R7), as in
X& operator=(this X& self, const X& o), andselfisn't counted in the "exactly one".
Footnote 83 points out that neither a template assignment operator nor an assignment operator with an rvalue reference parameter is a copy assignment operator, so they don't suppress the implicit declaration of the copy assignment operator. They take part in overload resolution together with it, and if one of them is selected it is used for the assignment.
Notes 1 and 3 say a class can declare several forms. Note 2 is about the example above: when the copy assignment operator has only an X& parameter, a const object can't be assigned to an X.
Implicit declaration (¶2, ¶4–¶6)#
Copy assignment (¶2)#
¶2 If a class has no user-declared (user-declared) copy assignment operator and is not an anonymous union, the compiler implicitly declares one:
- if the class has a user-declared move constructor or move assignment operator, it is defined as deleted (as if
= delete); - otherwise it is defaulted (its definition is generated by the compiler). In that case, if the class has a user-declared copy constructor or destructor, this implicit generation is deprecated ([depr.impldec]).
Its form is usually X& X::operator=(const X&), provided that:
- ¶2.1 each direct base class
Bhas a copy assignment operator whose parameter isconst B&,const volatile B&orB; and - ¶2.2 each non-static data member of class type
M(or array thereof) has a copy assignment operator whose parameter isconst M&,const volatile M&orM.
Otherwise the form is X& X::operator=(X&). Footnote 84 points out that, as a result, the reference parameter of the implicit version can't bind to a volatile lvalue ([diff.class]).
Only direct bases and non-static data members are considered here, whereas the copy constructor looks at all potentially constructed subobjects, including virtual bases. The reason is that assignment doesn't distinguish a most derived object from a base class subobject; virtual bases are handled along the way by the assignment operators of the direct bases (see ¶12).
Move assignment (¶4–¶5)#
¶4 If the class definition does not explicitly declare a move assignment operator, a defaulted one is implicitly declared if and only if all of the following hold:
- ¶4.1 it is not an anonymous union;
- ¶4.2 there is no user-declared copy constructor;
- ¶4.3 there is no user-declared move constructor;
- ¶4.4 there is no user-declared copy assignment operator;
- ¶4.5 there is no user-declared destructor.
¶5 Its form is X& X::operator=(X&&).
#include <type_traits>
struct S1 {
int a;
S1& operator=(const S1&) = default;
}; // no move assignment; rvalue assignment calls copy assignment
struct S2 {
int a;
S2& operator=(const S2&) = default;
S2& operator=(S2&&) = default; // explicitly defaulted
};
static_assert(std::is_move_assignable_v<S1>);
static_assert(std::is_move_assignable_v<S2>);
int main() { }Example 2 in the standard shows that = default also counts as user-declared, so S1 has no implicit move assignment operator; if you need one, default it explicitly as S2 does. std::is_move_assignable_v<S1> is still true, because it only checks whether an rvalue can be assigned, and an rvalue can bind to const S1&.
The same goes for a class that writes X& operator=(X): it is a user-declared copy assignment operator, so no move assignment operator is implicitly declared (¶4.4). Rvalue assignment is still efficient, though, since the argument is move-constructed into the parameter.
¶6 The implicitly-declared copy/move assignment operator has return type X& and is an inline public member of its class.
When they are defined as deleted (¶7)#
#include <string>
struct C { const int c; };
struct R { int& r; };
struct CS { const std::string s; };
union U { std::string s; int i; U() : i(0) { } ~U() { } };
void f(C& c1, C& c2, R& r1, R& r2,
CS& s1, CS& s2, U& u1, U& u2) {
c1 = c2; // error: ¶7.1
r1 = r2; // error: ¶7.2
s1 = s2; // error: ¶7.3
u1 = u2; // error: ¶7.3
}¶7 A defaulted copy/move assignment operator for class X is defined as deleted if X has any of the following:
- ¶7.1 a non-static data member of const non-class type (or multidimensional array thereof);
- ¶7.2 a non-static data member of reference type;
- ¶7.3 a direct non-static data member of class type
M(or multidimensional array thereof) or a direct base classMthat can't be copied/moved: overload resolution to find its assignment operator finds no usable candidate; or it is a variant member (variant member, a member of a union) and the selected function is non-trivial.
Each has a direct reason:
- ¶7.1: a const scalar can't be assigned. A member of const class type (like
CS::s) is handled by ¶7.3:operator=is not a const member function, so overload resolution for calling it on a const object fails. - ¶7.2: a reference can't be rebound. The memberwise assignment
r = other.rwould only assign the value of one referenced object to another, not makerrefer elsewhere. That is almost never what the user wants, so it is deleted outright. Copy construction has no such problem: the new object's reference simply binds to the same object. - The variant member clause of ¶7.3: a union doesn't know which member is active and can only copy bytes (¶13), so when some member's assignment is non-trivial, the only option is to delete it.
Note 4: a defaulted move assignment operator that is defined as deleted is ignored by overload resolution, so rvalue assignment can use copy assignment instead.
Reference or const members, but still assignable
Replace reference members with std::reference_wrapper<T> or pointers; replace const members with private non-const members plus a read-only accessor.
A derived class always hides the base class operator= (¶8)#
struct B { B& operator=(int); };
struct D : B { };
struct E : B { using B::operator=; };
void k(D& d, E& e) {
d = 1; // error: D::operator= hides B::operator=(int)
e = 1; // OK
}¶8 Because a copy/move assignment operator is always implicitly declared when the user doesn't declare one, a base class copy/move assignment operator is always hidden by the corresponding assignment operator of a derived class ([over.assign]).
Name hiding works by name, so the operator= implicitly declared in D hides all of the base's operator=, including B::operator=(int). To use them in the derived class, write a using-declaration as E does.
Note 5 adds that such a using-declaration never suppresses the implicit declaration of the derived class's own assignment operators, even if the base class operator it brings in would look like a copy or move assignment operator in the derived class.
Trivial assignment operators (¶9)#
#include <type_traits>
struct S {
S& operator=(const S&) & = default;
int x;
};
struct T {
T& operator=(this T&, const T&) = default;
int x;
};
static_assert(std::is_trivially_copy_assignable_v<S>);
static_assert(std::is_trivially_copy_assignable_v<T>);
int main() { }¶9 A copy/move assignment operator can be trivial only if it is not user-provided (user-provided, user-declared and not defaulted or deleted on its first declaration), and in addition:
- ¶9.1 the class has no virtual functions and no virtual base classes;
- ¶9.2 the assignment operator selected for each direct base class is a direct member of that base and is trivial;
- ¶9.3 the assignment operator selected for each non-static data member of class type (or array thereof) is trivial.
A trivial assignment operator amounts to copying the object's bytes. The example above shows that adding a & qualifier or using an explicit object parameter when defaulting (the two differences [dcl.fct.def.default]/2 allows) doesn't affect triviality.
Virtual functions make assignment non-trivial for a reason similar to copy construction: with Base& b = derived; b = other_base;, a byte-wise copy would overwrite derived's vtable pointer. The assignment operator has to keep the target object's vtable pointer and copy only the data members.
Implicit definition (¶10–¶14)#
¶10 An implicitly-defined copy/move assignment operator is constexpr.
¶11 Before a defaulted assignment operator is implicitly defined, all the non-user-provided copy/move assignment operators of its direct bases and non-static data members are implicitly defined first. An implicitly-declared version has an implied exception specification (note 6, [except.spec]).
Non-unions: memberwise assignment (¶12)#
¶12 The implicit assignment operator of a non-union class first assigns the direct bases in the order of the base-specifier-list, then the direct non-static data members in declaration order. Let x be the function's parameter, or, for move assignment, an xvalue referring to the parameter. Each subobject is handled according to its type:
- ¶12.1 class type: as if
operator=were called with the subobject as the object expression and the corresponding subobject ofxas the argument, and as if with explicit qualification, that is, without virtual dispatch; - ¶12.2 an array: each element is assigned;
- ¶12.3 a scalar: the built-in assignment operator is used.
Whether virtual base class subobjects are assigned more than once is unspecified unspecified:
#include <cstdio>
struct V {
V& operator=(const V&) {
std::puts("V::operator=");
return *this;
}
};
struct A : virtual V { };
struct B : virtual V { };
struct C : B, A { };
int main() {
C c1, c2;
c1 = c2; // is V::operator= called once or twice?
}Clang 23 prints it twice: C's implicit assignment calls B::operator= and then A::operator=, and both assign V. Construction doesn't have this problem because a constructor has two versions, one for complete objects and one for base subobjects, and a virtual base is constructed only once, by the most derived class ([class.base.init]); an assignment operator has only one version. Avoiding the repeated assignment requires writing it by hand, which is one reason virtual bases are best kept free of data.
Unions: copying the object representation (¶13)#
union U { int i; float f; };
int main() {
U a, b;
a.i = 1;
b.f = 2.0f;
b = a; // b.i becomes b's active member
return b.i - 1;
}¶13 The implicit assignment operator of a union copies the whole object representation. If the source and target are not the same object, then for each object nested within the source, a corresponding object is created in the target, and its lifetime begins before the copy.
The only difference from the copy constructor ([class.copy.ctor]/16) is self-assignment: with u = u, the active member is already there and needn't be created.
¶14 The implicitly-defined assignment operator returns the object assigned to, that is, *this.
Hand-written assignment operators: self-assignment and exception safety#
The standard places no requirements on user-written assignment operators, but there are two classic problems. Memberwise assignment is naturally safe against self-assignment, since each member is assigned to itself; hand-written resource management code is easy to get wrong:
#include <cstring>
struct Str {
char* p;
explicit Str(const char* s)
: p(new char[std::strlen(s) + 1]) { std::strcpy(p, s); }
~Str() { delete[] p; }
Str(const Str& o) : Str(o.p) { }
Str& operator=(const Str& o) {
delete[] p; // on self-assignment this frees o.p too
p = new char[std::strlen(o.p) + 1]; // UB: reads freed memory
std::strcpy(p, o.p);
return *this;
}
};
int main() {
Str s("hello");
Str& alias = s;
s = alias;
}AddressSanitizer reports a heap-use-after-free here. Copy-and-swap solves both self-assignment and strong exception safety:
#include <cstring>
#include <utility>
struct Str {
char* p;
explicit Str(const char* s)
: p(new char[std::strlen(s) + 1]) { std::strcpy(p, s); }
~Str() { delete[] p; }
Str(const Str& o) : Str(o.p) { }
Str(Str&& o) noexcept : p(std::exchange(o.p, nullptr)) { }
Str& operator=(Str o) noexcept { // copy assignment operator (¶1)
std::swap(p, o.p); // can't fail
return *this; // old resource destroyed with o
}
};
int main() {
Str s("hello"), t("world");
s = t; // copy-constructs the parameter, then swaps
s = Str("tmp"); // move-constructs the parameter, then swaps
return std::strcmp(s.p, "tmp");
}An operator= with a by-value parameter serves as both copy assignment and move assignment, at the cost of one extra move construction each time. Performance-sensitive classes usually write separate const X& and X&& versions.
When you hand-write a derived class's assignment operator, you must call B::operator=(o) explicitly. The compiler doesn't add the assignment of the base part for you, unlike a constructor, which default-constructs bases automatically.
Forbidding assignment to rvalues#
Built-in assignment requires the left operand to be a modifiable lvalue, but a class's implicit assignment operator has no ref-qualifier, so f() = x; and std::string("a") = "b"; both compile. A defaulted assignment operator can be given a & qualifier ([dcl.fct.def.default]/2) so that only lvalues can be assigned:
struct S {
S& operator=(const S&) & = default;
int x;
};
S f();
void g() {
S a{};
a = S{}; // OK
f() = S{}; // error: &-qualified operator= requires an lvalue
}The standard library doesn't do this, for compatibility. A newly designed value type can add & to its assignment operators and catch mistakes like assigning to a temporary at compile time.
Implementation view#
Trivial assignment and tail padding
In code generation a trivial copy/move assignment is just a byte copy, but there is an ABI detail. The Itanium C++ ABI lets a derived class's members be placed in a base class's tail padding, so a base's data size (dsize) can be smaller than its sizeof. So when the object being assigned may be a potentially-overlapping subobject (potentially-overlapping subobject), the compiler copies only dsize bytes, since otherwise it would overwrite the derived class's members. The guarantee in [basic.types.trivial] that a byte-wise copy preserves the value also applies only to objects that are not potentially overlapping, and calling memcpy yourself has the same precondition.
History#
History
- C++98 already had the copy assignment operator and its degraded
X&form. Back then, const or reference members made the implicit assignment ill-formed when used. - C++11 introduced move assignment and replaced "implicit definition is ill-formed" with "defined as deleted"; declaring a move operation deletes the implicit copy assignment; with a user-declared copy constructor or destructor, the implicit copy assignment is deprecated; defaulted assignment operators may carry a
&qualifier. - C++20 says that when a union is implicitly assigned, the corresponding members in the target begin their lifetime (P0593R6).
- C++23 introduced explicit object parameters (P0847R7), which defaulted assignment operators can use as well; implicitly-defined assignment operators became unconditionally
constexpr.
Common misconceptions#
Thinking const members only affect assignment
A const member deletes assignment, and std::vector's insert and erase and std::sort all require elements to be move-assignable, so the type can't be used there either. Classes meant to have value semantics should avoid const data members.
Virtual assignment operators
Declaring operator= virtual is almost always a design mistake. A derived class's operator=(const Derived&) has a different parameter type and doesn't override the base's operator=(const Base&). Polymorphic types should usually forbid assignment (= delete) and provide clone() instead.
Questions#
Question 1
struct A { A& operator=(A); }; // by value
struct B { A a; };B's implicit copy assignment operator have? When a B is move-assigned, is a moved or copied?
Answer
The parameter type of A::operator=(A) is A, which satisfies ¶2.2, so B's implicit copy assignment is B& operator=(const B&). B has no user-declared special member functions at all, so by ¶4 it also has an implicit move assignment B& operator=(B&&).
When that move-assigns a, it selects A::operator=(A) with an xvalue argument, and the parameter A would normally be initialized by the move constructor. But A has a user-declared copy assignment operator, so it has no implicit move constructor ([class.copy.ctor]/8), and the parameter can only be copy-constructed. The result is that moving a B actually copies a.
Question 2
¶7 deletes the assignment operators of a class with a reference member, but not its copy constructor. Why?
Answer
Copy construction creates a new object whose reference member binds to the object the source's reference is bound to; the semantics are clear. Assignment modifies an existing object, and a reference can't change once bound, so r = o.r only modifies the value of the referenced object. After such an assignment the two objects aren't equal, and a third-party object has been changed along the way, so it is deleted by default and the user decides the semantics.
Summary#
| Copy assignment | Move assignment | |
|---|---|---|
| Recognized by | Non-static non-template; one non-object parameter: X or cv X& |
Non-static non-template; one non-object parameter: cv X&& |
| Implicitly declared when | No user-declared copy assignment | No user-declared copy constructor, move constructor, copy assignment or destructor |
| Form | X& operator=(const X&), or X& operator=(X&) when necessary |
X& operator=(X&&) |
| Deleted when | A move operation is declared; const scalar member; reference member; a direct member or base can't be assigned | The last three as for copy; once deleted, ignored by overload resolution |
| Trivial when | Not user-provided, no virtual functions or virtual bases, the selected base and member assignments are all trivial | Same |
| Implicit definition | Bases first, then members, in declaration order; virtual bases may be assigned several times; returns *this |
Same, with the source as an xvalue |