内存管理库
第 20 章导读:<memory>、<memory_resource>、<scoped_allocator> 各管什么,它们怎样建立在核心语言的对象模型之上,以及读库条款时 Constraints、Mandates、Preconditions 等要素各意味着什么。
本节要点
- 第 20 章是对象模型的库接口:分配器协议、显式开始对象生命周期的函数、智能指针、内存资源都在这里。
- 读库条款时先分清要素:Constraints 不满足则函数不参与重载决议,Mandates 不满足则程序非良构,Preconditions 不满足则是未定义行为。
- C++26 的加固前置条件在加固实现中会被检查并终止程序,在其他实现中违反它仍是未定义行为;本章只有少数函数用它。
malloc族和内存资源会隐式创建对象,std::allocator<T>::allocate只开始数组对象的生命周期,元素要逐个构造。<memory>里有些声明的规范正文不在本章:特化内存算法在算法章,atomic<shared_ptr>在原子操作章。
第 20 章 [mem] 是标准库里离核心语言最近的一章。核心语言在 [intro.object]、[basic.life]、[basic.stc.dynamic]、[expr.new] 里规定对象何时存在、存储从哪里来、new 和 delete 做什么;本章把这些规则包装成可以组合的库组件。
本章地图 [mem.general]#
¶1 本章描述内存管理组件。¶2 的表 50 列出子条款与头文件的对应:
| 子条款 | 内容 | 头文件 | 本站笔记 |
|---|---|---|---|
| [memory] | 指针特征、对齐、显式生命周期管理、分配器协议、默认分配器、addressof、C 的 malloc 族 |
<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:把小整数存进指针的空闲位 |
<memory> |
[ptrtag] |
| [mem.composite.types] C++26 | indirect、polymorphic |
<memory> |
[mem.composite.types]、[indirect]、[polymorphic] |
| [mem.res] | memory_resource、polymorphic_allocator、池资源、单调缓冲资源 |
<memory_resource> |
[mem.res] |
| [allocator.adaptor] | scoped_allocator_adaptor |
<scoped_allocator> |
[allocator.adaptor] |
有几样东西声明在 <memory>,规范正文却在别处:
uninitialized_copy、construct_at、destroy_at等特化内存算法在算法章的 [specialized.algorithms],它们与 placement new 的关系见 [memory];atomic<shared_ptr<T>>在原子操作章的 [util.smartptr.atomic];operator new/operator delete、std::launder、bad_alloc在<new>,属于语言支持库 [support.dynamic]。
读库条款:违反各种要求的后果#
库条款很少直接用 shall 规定行为,而是给每个函数列出一组带斜体标签的要素([structure.specifications])。违反不同要素,后果完全不同:
| 要素 | 不满足时 | 本章的例子 |
|---|---|---|
| Constraints | 函数不参与重载决议,就像不存在一样 | unique_ptr<T[]> 的转换构造函数要求源指针也是数组版本、元素类型兼容 |
| Mandates | 程序非良构,必须诊断,通常由 static_assert 报出 |
default_delete<T>::operator() 要求 T 是完整类型 |
| Preconditions | 未定义行为 | unique_ptr::operator* 要求 get() != nullptr |
| Hardened preconditions C++26 | 在加固实现(hardened implementation)中作为契约检查,违反时终止;否则是未定义行为 | shared_ptr<T[]>::operator[] 要求 i >= 0,T 为 U[N] 时还要求 i < N |
| Constant When | 调用不是常量子表达式 | pointer_bits_available 要求对齐值是 2 的幂 |
Constraints 和 Mandates 的差别在泛型代码里最明显:
#include <memory>
#include <type_traits>
struct B {};
struct D : B {};
using UB = std::unique_ptr<B[]>;
using UD = std::unique_ptr<D[]>;
// Constraints 不满足:构造函数不是候选
static_assert(
!std::is_constructible_v<UB, UD>);
int main() {}#include <memory>
#include <type_traits>
struct Inc; // 不完整类型
using Del = std::default_delete<Inc>;
// 特征检测看不到 Mandates
static_assert(
std::is_invocable_v<Del, Inc*>);
void f(Inc* p) {
Del{}(p); // error: T 必须完整
}
int main() {}左边,Constraints 让那个构造函数从候选集中消失,is_constructible 能如实回答 false。右边,Mandates 不影响函数是否可调用,is_invocable 回答 true,真正调用时才在函数体里报错。
库前置条件违反导致的未定义行为,与核心语言的未定义行为地位相同([intro.abstract])。对空的 unique_ptr 解引用和 *static_cast<int*>(nullptr) 一样,优化器都可以假设它不发生。C++26 的标准库加固只把一部分前置条件改成了加固前置条件:本章里 shared_ptr<T[]>::operator[] 是,unique_ptr::operator* 和 operator-> 不是。
本章与核心语言的接口#
- 隐式创建对象:
malloc、calloc、realloc、memory_resource::allocate都会在返回的存储中隐式创建对象,并返回指向合适对象的指针([intro.object],implicitly creating objects)。start_lifetime_as不复制字节,在已有的存储上做同样的事([obj.lifetime])。 - 生命周期:
allocator<T>::allocate只开始数组对象的生命周期,不开始任何元素的生命周期([default.allocator])。元素要靠allocator_traits::construct逐个构造,默认就是construct_at,即 placement new。 - delete 表达式:
default_delete的效果就是对指针调用delete,所以 [expr.delete] 中关于不完整类型、非虚析构函数、delete与delete[]不匹配的未定义行为原样继承。 - 数据竞争:
shared_ptr的线程安全保证用 [intro.races] 的冲突和数据竞争来表述([util.smartptr.shared])。
本章的演进#
| 版本 | 主要变化 |
|---|---|
| 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 弃用 |
| C++14 | make_unique |
| C++17 | <memory_resource>、shared_ptr<T[]>;移除 auto_ptr |
| C++20 | to_address、assume_aligned、数组版 make_shared、*_for_overwrite、constexpr 的 allocator 和 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)、移除 allocator::is_always_equal 成员(P2868R3) |
| C++26 之后 | pointer_tag_pair(P3125R6) |
条款一览
- 20.1General 概述[mem.general]
- 20.2Memory 内存[memory]完成
- 20.2.1General 概述[memory.general]
- 20.2.2Header <memory> synopsis 头文件 <memory> 概要[memory.syn]
- 20.2.3Pointer traits 指针特征[pointer.traits]完成
- 20.2.4Pointer conversion 指针转换[pointer.conversion]
- 20.2.5Pointer alignment 指针对齐[ptr.align]完成
- 20.2.6Explicit lifetime management 显式生命周期管理[obj.lifetime]完成
- 20.2.7Allocator argument tag 分配器实参标签[allocator.tag]
- 20.2.8uses_allocator uses_allocator[allocator.uses]完成
- 20.2.9Allocator traits 分配器特征[allocator.traits]完成
- 20.2.10The default allocator 默认分配器[default.allocator]完成
- 20.2.11addressof addressof[specialized.addressof]
- 20.2.12C library memory allocation C 库内存分配[c.malloc]
- 20.3Pointer tagging 指针标记[ptrtag]完成
- 20.3.1Pointer tagging limits 指针标记限制[ptrtag.bits]
- 20.3.2Class template pointer_tag_pair 类模板 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]完成
- 20.4.1Unique-ownership pointers 独占所有权指针[unique.ptr]完成
- 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[unique.ptr.single]
- 20.4.1.4unique_ptr for array objects with a runtime length 运行时长度数组对象的 unique_ptr[unique.ptr.runtime]
- 20.4.1.5Creation 创建[unique.ptr.create]
- 20.4.1.6Specialized algorithms 特化的算法[unique.ptr.special]
- 20.4.1.7I/O I/O[unique.ptr.io]
- 20.4.2Shared-ownership pointers 共享所有权指针[util.sharedptr]完成
- 20.4.2.1Class bad_weak_ptr 类 bad_weak_ptr[util.smartptr.weak.bad]
- 20.4.2.2Class template shared_ptr 类模板 shared_ptr[util.smartptr.shared]完成
- 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 get_deleter[util.smartptr.getdeleter]
- 20.4.2.2.12I/O I/O[util.smartptr.shared.io]
- 20.4.2.3Class template weak_ptr 类模板 weak_ptr[util.smartptr.weak]完成
- 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 类模板 owner_less[util.smartptr.ownerless]完成
- 20.4.2.5Struct owner_hash 结构体 owner_hash[util.smartptr.owner.hash]
- 20.4.2.6Struct owner_equal 结构体 owner_equal[util.smartptr.owner.equal]
- 20.4.2.7Class template enable_shared_from_this 类模板 enable_shared_from_this[util.smartptr.enab]完成
- 20.4.3Smart pointer hash support 智能指针散列支持[util.smartptr.hash]
- 20.4.4Smart pointer adaptors 智能指针适配器[smartptr.adapt]完成
- 20.4.1Unique-ownership pointers 独占所有权指针[unique.ptr]完成
- 20.5Types for composite class design 组合类设计用类型[mem.composite.types]完成
- 20.5.1Class template indirect 类模板 indirect[indirect]草稿
- 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 与 T 比较[indirect.comp.with.t]
- 20.5.1.10Hash support 散列支持[indirect.hash]
- 20.5.2Class template polymorphic 类模板 polymorphic[polymorphic]草稿
- 20.5.1Class template indirect 类模板 indirect[indirect]草稿
- 20.6Memory resources 内存资源[mem.res]完成
- 20.6.1Header <memory_resource> synopsis 头文件 <memory_resource> 概要[mem.res.syn]
- 20.6.2Class memory_resource 类 memory_resource[mem.res.class]完成
- 20.6.3Class template polymorphic_allocator 类模板 polymorphic_allocator[mem.poly.allocator.class]完成
- 20.6.4Access to program-wide memory_resource objects 程序范围 memory_resource 对象的访问[mem.res.global]
- 20.6.5Pool resource classes 池资源类[mem.res.pool]完成
- 20.6.5.1Classes synchronized_pool_resource and unsynchronized_pool_resource 类 synchronized_pool_resource 与 unsynchronized_pool_resource[mem.res.pool.overview]
- 20.6.5.2pool_options data members pool_options 数据成员[mem.res.pool.options]
- 20.6.5.3Constructors and destructors 构造函数与析构函数[mem.res.pool.ctor]
- 20.6.5.4Members 成员[mem.res.pool.mem]
- 20.6.6Class monotonic_buffer_resource 类 monotonic_buffer_resource[mem.res.monotonic.buffer]完成
- 20.7Class template scoped_allocator_adaptor 类模板 scoped_allocator_adaptor[allocator.adaptor]完成