Memory management library
A guide to Chapter 20: what <memory>, <memory_resource> and <scoped_allocator> each cover, how they build on the core language's object model, and what Constraints, Mandates, Preconditions and the other elements of a library clause mean.
Key points
- Chapter 20 is the library interface to the object model: the allocator protocol, functions that explicitly begin object lifetimes, smart pointers and memory resources all live here.
- When reading a library clause, first tell the elements apart: an unmet Constraints removes the function from overload resolution, an unmet Mandates makes the program ill-formed, and an unmet Preconditions is undefined behavior.
- C++26 hardened preconditions are checked in a hardened implementation and terminate the program; in other implementations violating one is still undefined behavior. Only a few functions in this chapter use them.
- The
mallocfamily and memory resources implicitly create objects;std::allocator<T>::allocatebegins only the lifetime of the array object, and the elements have to be constructed one by one. - Some declarations in
<memory>have their normative wording outside this chapter: the specialized memory algorithms are in the algorithms chapter,atomic<shared_ptr>in the atomic operations chapter.
Chapter 20 [mem] is the library chapter closest to the core language. The core language specifies in [intro.object], [basic.life], [basic.stc.dynamic] and [expr.new] when objects exist, where storage comes from and what new and delete do; this chapter wraps those rules into composable library components.
Map of the chapter [mem.general]#
¶1 The chapter describes components for memory management. Table 50 in ¶2 maps subclauses to headers:
| Subclause | Contents | Header | Notes on this site |
|---|---|---|---|
| [memory] | Pointer traits, alignment, explicit lifetime management, the allocator protocol, the default allocator, addressof, C's malloc family |
<cstdlib>, <memory> |
[memory], [pointer.traits], [ptr.align], [obj.lifetime], [allocator.uses], [allocator.traits], [default.allocator] |
| [smartptr] | unique_ptr, shared_ptr, weak_ptr, out_ptr / inout_ptr |
<memory> |
[smartptr], [unique.ptr], [util.sharedptr] |
| [ptrtag] C++29 | pointer_tag_pair: storing a small integer in a pointer's unused bits |
<memory> |
[ptrtag] |
| [mem.composite.types] C++26 | indirect, polymorphic |
<memory> |
[mem.composite.types], [indirect], [polymorphic] |
| [mem.res] | memory_resource, polymorphic_allocator, pool resources, the monotonic buffer resource |
<memory_resource> |
[mem.res] |
| [allocator.adaptor] | scoped_allocator_adaptor |
<scoped_allocator> |
[allocator.adaptor] |
A few things are declared in <memory> but specified elsewhere:
- the specialized memory algorithms such as
uninitialized_copy,construct_atanddestroy_atare in [specialized.algorithms] in the algorithms chapter; their relation to placement new is covered in [memory]; atomic<shared_ptr<T>>is in [util.smartptr.atomic] in the atomic operations chapter;operator new/operator delete,std::launderandbad_allocare in<new>, part of the language support library [support.dynamic].
Reading library clauses: what violating each requirement means#
Library clauses rarely specify behavior with a plain "shall"; instead each function gets a list of elements with italic labels ([structure.specifications]). Violating different elements has completely different consequences:
| Element | When not met | Example from this chapter |
|---|---|---|
| Constraints | The function does not participate in overload resolution, as if it did not exist | The converting constructor of unique_ptr<T[]> requires the source pointer to be an array version too, with a compatible element type |
| Mandates | The program is ill-formed and must be diagnosed, usually by a static_assert |
default_delete<T>::operator() requires T to be a complete type |
| Preconditions | Undefined behavior | unique_ptr::operator* requires get() != nullptr |
| Hardened preconditions C++26 | Checked as a contract in a hardened implementation (hardened implementation), terminating on violation; undefined behavior otherwise | shared_ptr<T[]>::operator[] requires i >= 0, and also i < N when T is U[N] |
| Constant When | The call is not a constant subexpression | pointer_bits_available requires the alignment to be a power of 2 |
The difference between Constraints and Mandates is most visible in generic code:
#include <memory>
#include <type_traits>
struct B {};
struct D : B {};
using UB = std::unique_ptr<B[]>;
using UD = std::unique_ptr<D[]>;
// Constraints not met: the constructor is not a candidate
static_assert(
!std::is_constructible_v<UB, UD>);
int main() {}#include <memory>
#include <type_traits>
struct Inc; // incomplete type
using Del = std::default_delete<Inc>;
// trait detection cannot see Mandates
static_assert(
std::is_invocable_v<Del, Inc*>);
void f(Inc* p) {
Del{}(p); // error: T must be complete
}
int main() {}On the left, Constraints removes the constructor from the candidate set, and is_constructible truthfully answers false. On the right, Mandates does not affect whether the function is callable; is_invocable answers true, and the error appears in the function body only when it is actually called.
Undefined behavior from violating a library precondition has the same standing as undefined behavior in the core language ([intro.abstract]). Dereferencing an empty unique_ptr is like *static_cast<int*>(nullptr): the optimizer may assume it does not happen. C++26 standard library hardening turned only some preconditions into hardened preconditions: in this chapter shared_ptr<T[]>::operator[] is one, unique_ptr::operator* and operator-> are not.
Interfaces between this chapter and the core language#
- Implicit object creation:
malloc,calloc,reallocandmemory_resource::allocateall implicitly create objects in the returned storage and return a pointer to a suitable object ([intro.object], implicitly creating objects).start_lifetime_asdoes the same on existing storage without copying bytes ([obj.lifetime]). - Lifetime:
allocator<T>::allocatebegins only the lifetime of the array object, not of any element ([default.allocator]). Elements must be constructed one by one throughallocator_traits::construct, which by default isconstruct_at, i.e. placement new. - Delete-expressions: the effect of
default_deleteis to calldeleteon the pointer, so the undefined behavior in [expr.delete] for incomplete types, non-virtual destructors and mismatcheddelete/delete[]carries over unchanged. - Data races: the thread-safety guarantees of
shared_ptrare stated in terms of the conflicts and data races of [intro.races] ([util.smartptr.shared]).
Evolution of the chapter#
| Version | Main changes |
|---|---|
| C++98 | std::allocator, auto_ptr, raw_storage_iterator, get_temporary_buffer |
| C++11 | unique_ptr, shared_ptr, weak_ptr, allocator_traits, pointer_traits, scoped_allocator_adaptor, align, addressof; auto_ptr deprecated |
| C++14 | make_unique |
| C++17 | <memory_resource>, shared_ptr<T[]>; auto_ptr removed |
| C++20 | to_address, assume_aligned, array make_shared, *_for_overwrite, constexpr allocator and construct_at, atomic<shared_ptr> |
| C++23 | start_lifetime_as, out_ptr / inout_ptr, allocate_at_least, constexpr unique_ptr |
| C++26 | indirect / polymorphic (P3019R14), is_sufficiently_aligned, owner_hash / owner_equal (P1901R2), constexpr shared_ptr (P3037R6), removal of the allocator::is_always_equal member (P2868R3) |
| After C++26 | pointer_tag_pair (P3125R6) |
Contents
- 20.1General[mem.general]
- 20.2Memory[memory]done
- 20.2.1General[memory.general]
- 20.2.2Header <memory> synopsis[memory.syn]
- 20.2.3Pointer traits[pointer.traits]done
- 20.2.4Pointer conversion[pointer.conversion]
- 20.2.5Pointer alignment[ptr.align]done
- 20.2.6Explicit lifetime management[obj.lifetime]done
- 20.2.7Allocator argument tag[allocator.tag]
- 20.2.8uses_allocator[allocator.uses]done
- 20.2.9Allocator traits[allocator.traits]done
- 20.2.10The default allocator[default.allocator]done
- 20.2.11addressof[specialized.addressof]
- 20.2.12C library memory allocation[c.malloc]
- 20.3Pointer tagging[ptrtag]done
- 20.3.1Pointer tagging limits[ptrtag.bits]
- 20.3.2Class template pointer_tag_pair[ptrtag.pair]
- 20.3.2.1General[ptrtag.pair.general]
- 20.3.2.2Constructors[ptrtag.pair.cons]
- 20.3.2.3Support for overaligned pointers[ptrtag.pair.overalign]
- 20.3.2.4Tagged pointer operations[ptrtag.pair.tagops]
- 20.3.2.5Accessors[ptrtag.pair.accessors]
- 20.3.2.6Swap[ptrtag.pair.swap]
- 20.3.2.7Comparisons[ptrtag.pair.comp]
- 20.3.2.8Tuple interface[ptrtag.pair.get]
- 20.4Smart pointers[smartptr]done
- 20.4.1Unique-ownership pointers[unique.ptr]done
- 20.4.1.1General[unique.ptr.general]
- 20.4.1.2Default deleters[unique.ptr.dltr]
- 20.4.1.3unique_ptr for single objects[unique.ptr.single]
- 20.4.1.4unique_ptr for array objects with a runtime length[unique.ptr.runtime]
- 20.4.1.5Creation[unique.ptr.create]
- 20.4.1.6Specialized algorithms[unique.ptr.special]
- 20.4.1.7I/O[unique.ptr.io]
- 20.4.2Shared-ownership pointers[util.sharedptr]done
- 20.4.2.1Class bad_weak_ptr[util.smartptr.weak.bad]
- 20.4.2.2Class template shared_ptr[util.smartptr.shared]done
- 20.4.2.2.1General[util.smartptr.shared.general]
- 20.4.2.2.2Constructors[util.smartptr.shared.const]
- 20.4.2.2.3Destructor[util.smartptr.shared.dest]
- 20.4.2.2.4Assignment[util.smartptr.shared.assign]
- 20.4.2.2.5Modifiers[util.smartptr.shared.mod]
- 20.4.2.2.6Observers[util.smartptr.shared.obs]
- 20.4.2.2.7Creation[util.smartptr.shared.create]
- 20.4.2.2.8Comparison[util.smartptr.shared.cmp]
- 20.4.2.2.9Specialized algorithms[util.smartptr.shared.spec]
- 20.4.2.2.10Casts[util.smartptr.shared.cast]
- 20.4.2.2.11get_deleter[util.smartptr.getdeleter]
- 20.4.2.2.12I/O[util.smartptr.shared.io]
- 20.4.2.3Class template weak_ptr[util.smartptr.weak]done
- 20.4.2.3.1General[util.smartptr.weak.general]
- 20.4.2.3.2Constructors[util.smartptr.weak.const]
- 20.4.2.3.3Destructor[util.smartptr.weak.dest]
- 20.4.2.3.4Assignment[util.smartptr.weak.assign]
- 20.4.2.3.5Modifiers[util.smartptr.weak.mod]
- 20.4.2.3.6Observers[util.smartptr.weak.obs]
- 20.4.2.3.7Specialized algorithms[util.smartptr.weak.spec]
- 20.4.2.4Class template owner_less[util.smartptr.ownerless]done
- 20.4.2.5Struct owner_hash[util.smartptr.owner.hash]
- 20.4.2.6Struct owner_equal[util.smartptr.owner.equal]
- 20.4.2.7Class template enable_shared_from_this[util.smartptr.enab]done
- 20.4.3Smart pointer hash support[util.smartptr.hash]
- 20.4.4Smart pointer adaptors[smartptr.adapt]done
- 20.4.1Unique-ownership pointers[unique.ptr]done
- 20.5Types for composite class design[mem.composite.types]done
- 20.5.1Class template indirect[indirect]draft
- 20.5.1.1General[indirect.general]
- 20.5.1.2Synopsis[indirect.syn]
- 20.5.1.3Constructors[indirect.ctor]
- 20.5.1.4Destructor[indirect.dtor]
- 20.5.1.5Assignment[indirect.assign]
- 20.5.1.6Observers[indirect.obs]
- 20.5.1.7Swap[indirect.swap]
- 20.5.1.8Relational operators[indirect.relops]
- 20.5.1.9Comparison with T[indirect.comp.with.t]
- 20.5.1.10Hash support[indirect.hash]
- 20.5.2Class template polymorphic[polymorphic]draft
- 20.5.1Class template indirect[indirect]draft
- 20.6Memory resources[mem.res]done
- 20.6.1Header <memory_resource> synopsis[mem.res.syn]
- 20.6.2Class memory_resource[mem.res.class]done
- 20.6.3Class template polymorphic_allocator[mem.poly.allocator.class]done
- 20.6.4Access to program-wide memory_resource objects[mem.res.global]
- 20.6.5Pool resource classes[mem.res.pool]done
- 20.6.6Class monotonic_buffer_resource[mem.res.monotonic.buffer]done
- 20.7Class template scoped_allocator_adaptor[allocator.adaptor]done