The birth and death of objects
When the compiler declares special member functions for a class, when initialization copies, moves or does nothing at all, and how noexcept moves, trivial copyability and the order of construction and destruction show up in real programs.
Key points
- If the user declares any of the destructor, copy constructor or copy assignment operator, the move operations are no longer implicitly declared, and passing an rvalue silently falls back to copying.
- A function that isn't declared and a function that is deleted are two different things: overload resolution can't see the former, and selecting the latter is an error.
- Initializing an object from a prvalue of the same type does nothing at all: the target is the prvalue's result object.
return local;may be elided (NRVO), and if it isn't, it moves. - When the move constructor isn't
noexcept,std::vectorcopies elements instead of moving them when it grows. - Writing an empty
~T() {}makes a type no longer trivially copyable; when you need an explicit declaration, use= default.
An empty destructor turns moves into copies#
#include <cstdio>
#include <utility>
struct Logged {
Logged() = default;
Logged(const Logged&) { std::puts("copy"); }
Logged(Logged&&) noexcept { std::puts("move"); }
};
struct WithDtor {
Logged l;
~WithDtor() {} // user-declared destructor: the move constructor is no longer implicitly declared
};
struct Plain {
Logged l; // nothing declared: has an implicit move constructor
};
int main() {
WithDtor a;
WithDtor b(std::move(a)); // copy: no move constructor, the implicit copy constructor is selected
Plain c;
Plain d(std::move(c)); // move
}The program prints copy, then move. WithDtor only adds a destructor that does nothing, and moving turns into copying. The reason lies in the rules for which functions the compiler declares for a class.
There are six special member functions: the default constructor, copy constructor, move constructor, copy assignment operator, move assignment operator, and destructor ([special]). When the user hasn't declared them, the compiler implicitly declares them under certain conditions, usually as defaulted, meaning generated by the compiler memberwise.
What the compiler declares for you#
Where each rule comes from:
- Default constructor: implicitly declared when there is no user-declared constructor at all ([class.default.ctor]/1).
- Copy constructor: implicitly declared when there is no user-declared copy constructor. If the class declares a move constructor or move assignment operator, the implicit copy constructor is defined as deleted. If the class has a user-declared copy assignment operator or destructor, implicitly declaring it as defaulted is deprecated ([class.copy.ctor]/6, [depr.impldec]).
- Move constructor: implicitly declared only if there is no user-declared copy constructor, copy assignment operator, move assignment operator or destructor ([class.copy.ctor]/8).
- Copy assignment, move assignment: symmetric with the two above ([class.copy.assign]/2, [class.copy.assign]/4).
- Destructor: implicitly declared when there is no user-declared destructor ([class.dtor]).
User-declared here includes declarations written = default and = delete. Laid out as a table:
| User declares ↓ / compiler provides → | Default ctor | Destructor | Copy ctor | Copy assign | Move ctor | Move assign |
|---|---|---|---|---|---|---|
| Nothing | Defaulted | Defaulted | Defaulted | Defaulted | Defaulted | Defaulted |
| Any constructor | Not declared | Defaulted | Defaulted | Defaulted | Defaulted | Defaulted |
| Default ctor | User | Defaulted | Defaulted | Defaulted | Defaulted | Defaulted |
| Destructor | Defaulted | User | Defaulted (deprecated) | Defaulted (deprecated) | Not declared | Not declared |
| Copy ctor | Not declared | Defaulted | User | Defaulted (deprecated) | Not declared | Not declared |
| Copy assign | Defaulted | Defaulted | Defaulted (deprecated) | User | Not declared | Not declared |
| Move ctor | Not declared | Defaulted | Deleted | Deleted | User | Not declared |
| Move assign | Defaulted | Defaulted | Deleted | Deleted | Not declared | User |
The table has two kinds of "absent", which must be kept apart:
- Not declared: the function doesn't exist, and overload resolution can't see it. A class that declares a destructor has no move constructor, so
T b(std::move(a));selects the copy constructor, sinceconst T&can also bind to an rvalue. The code compiles as usual; it just copies. - Deleted: the function exists and takes part in overload resolution, and selecting it is an error. For a class that declares move operations, the copy constructor is deleted, and
T b = a;simply fails to compile.
"Defaulted" in the table only says the function is declared as defaulted; it may still be defined as deleted. For example, if the class has a non-copyable member, the implicit copy constructor is deleted ([class.copy.ctor]/10). There is one exception: a defaulted move operation that is defined as deleted is excluded from the candidate set ([over.match.funcs.general]/9), so when moving is impossible it falls back to copying instead of being an error.
The Rules of 0, 3 and 5#
The table leads directly to three rules of thumb:
- Rule of 0: if a class only combines members that manage their own resources, such as
std::string,std::vectorandstd::unique_ptr, don't write any special members. The six functions the compiler generates operate memberwise and do the right thing; as long as the members' moves don't throw, the generated moves arenoexcepttoo. - Rule of 3 (C++98): if you need to customize any of the destructor, copy constructor or copy assignment operator (usually because you manage a resource by hand), you need to customize all three.
- Rule of 5 (C++11): add the move constructor and move assignment to those three. By the table, declaring any of the first three means the move operations are no longer implicitly declared, and without providing them explicitly you can only copy.
A polymorphic base class needs a virtual destructor, and a common way to write it is to explicitly default the rest:
#include <type_traits>
struct Base {
virtual ~Base() = default; // user-declared destructor: moves no longer implicitly declared
Base() = default;
Base(const Base&) = default; // so default all the rest explicitly
Base& operator=(const Base&) = default;
Base(Base&&) = default;
Base& operator=(Base&&) = default;
};
static_assert(std::is_nothrow_move_constructible_v<Base>);
int main() {}Whether a polymorphic base class should allow copying at all, to avoid slicing, is a design question, not a language rule.
Copy, move, or nothing at all#
When an object of type T is initialized from an expression e, what happens depends on the value category of e ([basic.lval]):
e is |
Examples | Result | Basis |
|---|---|---|---|
A prvalue of type T |
T(), f() returning T, T{1, 2} |
Nothing at all; the target is the result object of e |
[dcl.init]/15.6.1, [basic.lval]/5 |
An xvalue of type T |
std::move(a), return local; |
Move construction, or copy if there is no move constructor | Overload resolution |
An lvalue of type T |
a, *p, arr[0] |
Copy construction | Overload resolution |
| Another type | T x = 42; |
A prvalue is obtained via a converting constructor or conversion function, then as in the first row | [dcl.init] |
The first row is C++17's guarantee (P0135R1): a prvalue is no longer a temporary that needs copying but a way of initializing, ultimately constructing directly in the target's location. So types that can be neither copied nor moved, such as std::mutex, can still be returned by value from a factory function that returns a prvalue.
On top of that, [class.copy.elision] lists a few places where an implementation may elide a copy or move: return of a local object (called NRVO, named return value optimization), throw of a local object, copying coroutine parameters, and catch by value. These elisions are optional. In practice, GCC and Clang reliably perform NRVO when a function has a single returned variable.
When elision doesn't happen, there is a fallback rule: the name in return local; and throw local; is move-eligible and treated as an xvalue ([expr.prim.id.unqual]/15; simplified into this form by P2266R3 in C++23), so it moves rather than copies.
The cost of common forms (since C++17, GCC and Clang):
| Form | Cost |
|---|---|
T x = T(args);, T x = make(); (make returns a prvalue) |
1 construction |
T make() { T t; ...; return t; } |
1 construction (NRVO); 1 more move if NRVO doesn't happen |
T f(T p) { return p; } |
Parameters can't get NRVO; 1 more move |
return cond ? a : b; |
1 more copy; a conditional expression isn't a move-eligible name |
return std::move(t); |
1 more move, and it prevents NRVO |
f(T(args)), parameter by value |
1 construction; the parameter is the result object |
f(a), parameter by value, a an lvalue |
1 more copy |
noexcept moves and std::vector growth#
When std::vector grows it has to move the old elements to new memory. By [vector.modifiers]/2, when a single element is inserted at the end and an exception is thrown, there must be no effect as long as T is copy-insertable or is_nothrow_move_constructible_v<T> is true; this is the strong exception guarantee.
If elements were relocated with the move constructor and a move threw halfway through, the elements in the old memory would already have been moved out, and the original state couldn't be restored. So implementations move only when the move constructor is noexcept (or the type isn't copyable), and copy otherwise. The standard library expresses this choice with std::move_if_noexcept.
#include <cstdio>
#include <vector>
template<bool NoExcept>
struct T {
int id;
T(int i) : id(i) {}
T(const T& o) : id(o.id) { std::printf("copy%d ", id); }
T(T&& o) noexcept(NoExcept) : id(o.id) { std::printf("move%d ", id); }
};
int main() {
{
std::vector<T<false>> v;
v.reserve(2); v.emplace_back(1); v.emplace_back(2);
std::printf("growth (move may throw): ");
v.emplace_back(3); // copy1 copy2
std::puts("");
}
{
std::vector<T<true>> v;
v.reserve(2); v.emplace_back(1); v.emplace_back(2);
std::printf("growth (noexcept move): ");
v.emplace_back(3); // move1 move2
std::puts("");
}
}So move constructors and move assignment operators should almost always be noexcept. For move operations that are implicitly generated or = default, the exception specification is deduced from the members ([except.spec]), and it is automatically noexcept when the members' moves don't throw. That's another benefit of the Rule of 0.
Trivially copyable and memcpy#
A trivially copyable type can bypass its special member functions and be copied byte by byte. By [class.prop]/1, a class is trivially copyable if and only if it meets three conditions: it has at least one eligible copy or move constructor or copy or move assignment operator (eligible means not deleted and with constraints satisfied, see [special]); every such eligible function is trivial; and it has a trivial, non-deleted destructor.
Trivial roughly means the function is generated by the compiler and has nothing extra to do: it isn't user-provided, the class has no virtual functions or virtual base classes, and the corresponding operations of all subobjects are trivial too ([class.copy.ctor]/12). A = default written on the first declaration doesn't count as user-provided and doesn't affect triviality; writing an empty ~T() {} breaks it.
#include <cstring>
#include <string>
#include <type_traits>
struct P { int x; double y; };
struct P2 { int x; P2() = default; P2(const P2&) = default; ~P2() = default; }; // still trivial
struct P3 { int x; ~P3() {} }; // user-provided destructor: no longer trivially copyable
struct P4 { std::string s; }; // non-trivial member: no longer trivially copyable
struct P5 { int x; virtual void f() {} }; // virtual function: no longer trivially copyable
static_assert(std::is_trivially_copyable_v<P>);
static_assert(std::is_trivially_copyable_v<P2>);
static_assert(!std::is_trivially_copyable_v<P3>);
static_assert(!std::is_trivially_copyable_v<P4>);
static_assert(!std::is_trivially_copyable_v<P5>);
int main() {
P a{1, 2.0}, b{};
std::memcpy(&b, &a, sizeof(P)); // OK: b gets a's value
return b.x == 1 ? 0 : 1;
}For trivially copyable types, [basic.types.trivial]/3 and [basic.types.trivial]/4 guarantee that if an object's bytes are copied into an array of char, unsigned char or std::byte and back, or copied directly from one object to another (not potentially-overlapping) object, the target object gets the source object's value. Copying structs with std::memcpy, std::bit_cast, and binary serialization all rest on this.
There are ABI consequences too. [class.temporary]/3 allows implementations to create an extra temporary for passing arguments and returning values, provided the type's eligible copy and move constructors are all trivial and its destructor is trivial or deleted. Mainstream ABIs use this to pass such small objects in registers. An empty user destructor not only removes the basis for memcpy, it may also turn an object the size of two ints from being passed in registers to being passed through memory.
Order of construction and destruction#
By [class.base.init]/15 and [class.dtor]:
- Construction: virtual base classes (constructed only by the most derived class, depth-first, left to right), then direct base classes (in declaration order), then non-static data members (in declaration order), and finally the constructor body.
- Destruction: the destructor body, then non-static data members (in reverse declaration order), then direct base classes (in reverse declaration order), and finally virtual base classes (destroyed only by the most derived class, in reverse order of construction).
During construction and destruction, the object is, in the polymorphic sense, of the class the current constructor or destructor belongs to ([class.cdtor]); virtual calls, typeid and dynamic_cast can't see the more derived parts. If an exception is thrown partway through construction, the subobjects already constructed are destroyed in reverse order, and the object's own destructor isn't called; the exception is when the body of a delegating constructor throws, at which point the target constructor has completed, and the object's destructor is called ([except.ctor]).
Tracing line by line#
Below, a type that prints from every special member function puts the rules above to work on a concrete program. Each object gets a new number #n when it is constructed.
#include <cstdio>
#include <utility>
#include <vector>
struct Tr {
static inline int next = 0;
int id;
Tr() : id(++next) { std::printf(" #%d Tr()\n", id); }
Tr(const Tr& o) : id(++next) { std::printf(" #%d Tr(const Tr&) <- #%d\n", id, o.id); }
Tr(Tr&& o) noexcept : id(++next) { std::printf(" #%d Tr(Tr&&) <- #%d\n", id, o.id); }
Tr& operator=(const Tr& o) { std::printf(" #%d = copy #%d\n", id, o.id); return *this; }
Tr& operator=(Tr&& o) noexcept { std::printf(" #%d = move #%d\n", id, o.id); return *this; }
~Tr() { std::printf(" #%d ~Tr()\n", id); }
};
Tr factory() { Tr t; return t; } // NRVO possible
Tr pass(Tr p) { return p; } // parameter: can only be implicitly moved
struct Holder {
Tr m;
Holder(Tr x) : m(std::move(x)) {}
};
int main() {
std::puts("[1] Tr a = factory();");
Tr a = factory();
std::puts("[2] Tr b = pass(a);");
Tr b = pass(a);
std::puts("[3] Holder h(Tr{});");
Holder h(Tr{});
std::puts("[4] a = pass(Tr{});");
a = pass(Tr{});
std::puts("[5] vector");
std::vector<Tr> v;
v.reserve(1);
v.push_back(b);
v.push_back(std::move(a));
std::puts("[6] end of main");
}Below is the output with Clang 23 + libc++, explained section by section.
[1] Tr a = factory();
#1 Tr()factory() is a prvalue, and a is its result object ([dcl.init]/15.6.1). The return t; in factory meets the conditions for NRVO (¶1.1 of [class.copy.elision]/1), and Clang constructs t directly in a's storage: just one construction throughout. Compiled with -fno-elide-constructors, there would be an extra Tr(Tr&&) from t to a and an extra destruction here.
[2] Tr b = pass(a);
#2 Tr(const Tr&) <- #1
#3 Tr(Tr&&) <- #2
#2 ~Tr()a is an lvalue, so the by-value parameter p is copy-constructed (#2). In return p;, a parameter can't get NRVO, but p is move-eligible, so the return value is move-constructed, and the return value's result object is b (#3). Finally the parameter #2 is destroyed. Whether parameters are destroyed when the function returns or at the end of the full-expression containing the call is implementation-defined ([expr.call]/7); in the Itanium ABI the caller destroys them at the end of the full-expression.
[3] Holder h(Tr{});
#4 Tr()
#5 Tr(Tr&&) <- #4
#4 ~Tr()The argument Tr{} is a prvalue, and the parameter x is its result object (#4), with no copy. The mem-initializer m(std::move(x)) direct-initializes the member from an xvalue, so it is move-constructed (#5). Then the parameter #4 is destroyed. The member m must be located inside h and can't take over the parameter's storage, so this move can't be avoided. That one move is the cost of taking by value and then moving into a member.
[4] a = pass(Tr{});
#6 Tr()
#7 Tr(Tr&&) <- #6
#1 = move #7
#7 ~Tr()
#6 ~Tr()Tr{} becomes the parameter p directly (#6), and return p; implicitly moves into the return value (#7). This time the return value isn't used to initialize an object but as the argument of operator=(Tr&&). A reference has to bind to the prvalue, so temporary materialization happens ([class.temporary]/2), and #7 is that temporary. Then it is move-assigned to a, whose number is still #1, because assignment doesn't create an object. At the end of the full-expression, the temporary #7 is destroyed first, then the parameter #6.
[5] std::vector
#8 Tr(const Tr&) <- #3
#9 Tr(Tr&&) <- #1
#10 Tr(Tr&&) <- #8
#8 ~Tr()In v.push_back(b), b is an lvalue and is copied into the buffer of capacity 1 (#8). At v.push_back(std::move(a)) the capacity is insufficient and the vector must grow. libc++ first constructs the new element in the new buffer (#9, moved from a), then moves the old element over (#10, moved from #8, because Tr's move constructor is noexcept), and finally destroys the old element #8. Remove the noexcept from Tr(Tr&&), and the #10 line becomes Tr(const Tr&).
[6] End of main
#9 ~Tr()
#10 ~Tr()
#5 ~Tr()
#3 ~Tr()
#1 ~Tr()Local variables are destroyed in reverse order of construction ([stmt.jump]): first v, then h (member m is #5), then b (#3), and finally a (#1). v destroys v[1] (#9) before v[0] (#10); the destruction order of elements is up to the library.
In total 10 objects were constructed and there were 10 destructions. Even when copy elision happens, every construction corresponds to exactly one destruction ([class.copy.elision]/1 Note 1).
Summary#
- Use the Rule of 0 whenever you can.
- When you need a virtual destructor, restore the rest explicitly with
= default, or explicitly= deletecopying. - Write move operations as
noexcept; you can check withstatic_assert(std::is_nothrow_move_constructible_v<T>). - Have factory functions return a prvalue (
return T(...);) or a single local variable; don't writereturn std::move(local);. - If you want to copy with
memcpy, keep the type trivially copyable: don't write an empty destructor, use= default. - Don't put business-logic side effects in a copy constructor; whether it gets called depends on copy elision.
Value categories and the semantics of prvalues are covered in Value categories in practice.