跳转到内容
新建笔记

C++ 第20B册 内存分配与智能指针

C++ 第20B册 内存分配与智能指针

跳转到“C++ 第20B册 内存分配与智能指针”

本册以用户提供的 ISO/IEC 14882:2003(E) 与 ISO/IEC 14882:2011(E) 正式 PDF 为唯一规范底本,重建 C++03 分配器、原始存储和 auto_ptr,以及 C++11 内存工具和智能指针的中文逐条笔记。目标是把存储、对象生存期、销毁策略和所有权分清,并能追到同版条款。这里的“03”“11”分别指两份正式版,不把后续缺陷报告、C++14 以后新增接口或当前实现行为倒填成原文。

本册已完成下表所列全部范围的独立静态审校。代码是声明、原标准等效算法或原创静态示例,均未编译、运行或用实验推导规范。

正式版本册条款印刷页PDF 实页范围状态
200320.1.5360–363388–391已完成
200320.4–20.4.6374–381402–409已完成
201120.6–20.6.13525–540541–556已完成
201120.7–20.7.2.6540–566556–582已完成

范围核对:03 正式目录的 20.4 下含默认分配器、原始存储迭代器、临时缓冲、三个未初始化算法、auto_ptr 与 C 库;11 正式目录列 20.6 Memory、20.7 Smart pointers,细分编号由同版正文标题逐项核对。本册不含 03 20.5 日期时间、11 20.8 函数对象。11 17.6.3.5 的通用 Allocator 要求只作为必要交叉引用,不伪装为 20.6 的正文。已知 03 PDF 缺失印刷页均不落入本册范围。

定位方式:每节给出原条号和方括号标签;“p”表示该小节的编号款,不是页码;表号、脚注号沿用相应正式版。中文是解释性重述。原文用 Returns 标记的 void 成员语义,不擅自解释成 C++ 返回值;规范动作与源码声明分开读。排版断字、浅字和识别丢失的 ~、_、花括号以 PDF 像素核对后恢复,不当成新的标准争议。本册记录的字形、声明差异,只能证明用户提供的PDF副本有相应可见文字;页图可以排除纯文本抽取层错误,不能据此断言ISO原始出版物有错误。

20.1.5 分配器要求 [lib.allocator.requirements]

跳转到“20.1.5 分配器要求 [lib.allocator.requirements]”

来源:03 印刷 360–363,PDF 388–391;p1–5、表31、表32、脚注214。

p1:allocator 是保存分配模型信息的对象。模型不仅决定分配、释放原语,还决定指针类型、指针差类型和对象大小类型。第23章的容器都以分配器为模板参数。

p2:表31约定后续要求中的记号,表32给出接口契约;分配器上的操作预期为摊销常量时间。这里不是承诺一次向操作系统申请内存的实际耗时恒定。

表31完整记号重述:

记号含义
T, U任意类型
X为 T 服务的 allocator 类
Y相应的、为 U 服务的 allocator 类
tconst T& 类型的值
a, a1, a2X& 类型的值
bY 类型的值
pX::pointer,由 a1.allocate 获得,且 a1 == a
q从 p 转换所得的 X::const_pointer
r由 *p 得到的 X::reference
s由 *q 或从 r 转换得到的 X::const_reference
u由 Y::allocate 得到的 Y::const_pointer,或 0
nX::size_type 的值

表32完整要求重述:

表达式或类型类型与合同
X::pointer指向 T 的指针类型
X::const_pointer指向 const T 的指针类型
X::referenceT&
X::const_referenceT const&
X::value_type与 T 相同
X::size_type无符号整数类型,可表示分配模型中最大对象的大小
X::difference_type有符号整数类型,可表示模型内任意两指针之差
typename X::template rebind<U>::other为 Y;所有 U(包括 T)都须满足反向 Y::template rebind<T>::other 为 X
a.address(r)返回 X::pointer
a.address(s)返回 X::const_pointer
a.allocate(n)、a.allocate(n,u)返回 X::pointer;分配容纳 n 个 T 的存储,但不构造对象;可抛适当异常;结果是随机访问迭代器;n == 0 时结果未指定
a.deallocate(p,n)返回值不使用;须先销毁该区域中的全部 n 个 T;n 须与分配时一致;不得抛异常;注指出 p 不得为空
a.max_size()返回 X::size_type,即能够有意义地传给 X::allocate() 的最大值
a1 == a2返回 bool;当且仅当双方分配的存储可由另一方释放时为真
a1 != a2等价于 !(a1 == a2)
X()建立默认实例,并假定有析构函数
X a(b)跨类型构造;后置条件 Y(a) == b
a.construct(p,t)返回值不使用;作用为 new((void*)p) T(t)
a.destroy(p)返回值不使用;作用为 ((T*)p)->~T()

脚注214解释设计意图:即便 sizeof(T) 很小,allocate 也应有效率地分配一个 T 的存储。这不是保证每次调用恰好触发一次全局 operator new。

另有页底说明(03印刷363,PDF391):容器无需自行维护自己的空闲链表。这份PDF副本中该说明的编号不可清楚辨认,故按页面定位保留其内容,不补猜脚注号。

p3:rebind 起到“typedef 模板”的作用;若 Allocator 是 SomeAllocator<T>,则 Allocator::rebind<U>::other 应是 SomeAllocator<U>。

p4:03 容器实现还被允许额外假设两点:同一分配器类型的所有实例可互换且总比较相等;其 pointer、const_pointer、size_type、difference_type 分别就是 T*、T const*、size_t、ptrdiff_t。因此不能仅凭表32允许抽象指针,就断言所有符合03的标准容器必须接受有状态、不等值或 fancy-pointer 分配器。

p5:鼓励支持更一般的模型及不等值实例;若实现这样做,表32以外的额外要求,以及不等分配器实例下容器、算法的语义,由实现定义。

静态关系图:

allocator<T> --allocate(n)--> 原始存储,尚无 n 个活的 T
原始存储 --construct(p,t)--> 对象生存期开始
活对象 --destroy(p)--> 对象生存期结束,存储仍归分配器
已清理存储 --deallocate(p,n)--> 释放
X<T> --rebind<U>::other--> Y<U>
Y<U> --rebind<T>::other--> X<T>

来源:03 印刷374,PDF402。<memory> 总览包含 allocator、allocator<void>、跨类型相等与不等比较、raw_storage_iterator、get_temporary_buffer、return_temporary_buffer、uninitialized_copy、uninitialized_fill、uninitialized_fill_n、auto_ptr。以下逐节保留这些接口,避免把总览中的签名丢掉。注意03 uninitialized_fill_n 返回 void,不能套用11的返回尾迭代器签名。

20.4.1 默认分配器 [lib.default.allocator]

跳转到“20.4.1 默认分配器 [lib.default.allocator]”

来源:03 印刷374–376,PDF402–404。下列声明按正式版语义恢复断字,未添加11的 noexcept、allocator_traits 或可变参数构造。

namespace std {
template<class T> class allocator;
template<> class allocator<void> {
public:
typedef void* pointer;
typedef const void* const_pointer;
typedef void value_type;
template<class U> struct rebind { typedef allocator<U> other; };
};
template<class T> class allocator {
public:
typedef size_t size_type;
typedef ptrdiff_t difference_type;
typedef T* pointer;
typedef const T* const_pointer;
typedef T& reference;
typedef const T& const_reference;
typedef T value_type;
template<class U> struct rebind { typedef allocator<U> other; };
allocator() throw();
allocator(const allocator&) throw();
template<class U> allocator(const allocator<U>&) throw();
~allocator() throw();
pointer address(reference x) const;
const_pointer address(const_reference x) const;
pointer allocate(size_type, allocator<void>::const_pointer hint = 0);
void deallocate(pointer p, size_type n);
size_type max_size() const throw();
void construct(pointer p, const T& val);
void destroy(pointer p);
};
}

allocator<void> 没有引用 void 的成员,因为 void& 无法成立;它不是供构造 void 对象使用的普通分配器实例。

20.4.1.1 allocator 成员 [lib.allocator.members]

跳转到“20.4.1.1 allocator 成员 [lib.allocator.members]”

p1–2:两个 address 重载分别返回 &x。这是03原文的表达式,不能把11明确的 addressof 保证悄悄移入此处。

p3–7:allocate(n,hint) 使用全局 ::operator new(size_t)。hint 必须为 0,或之前由成员 allocate 获得且尚未传给 deallocate 的值。返回指向大小为 n * sizeof(T)、适合 T 对齐的存储数组首元素的指针。调用全局分配函数的时机、次数和如何利用 hint 均未指定;hint 用于提高局部性只是实现可用的意图。无法获得存储时抛 bad_alloc。脚注216:在容器成员函数中,邻近元素地址常适合用作 hint。

p8–10:deallocate(p,n) 的 p 必须来自 allocate(),n 必须等于产生该 p 的那次首实参。作用是释放其存储;使用 ::operator delete(void*),但调用时机未指定。与20.1.5一起读:对象的析构是调用者先完成的动作,不由“归还存储”自动替代。

p11:max_size() 返回可能让 allocate(N,0) 成功的最大 N;不是当前空闲内存测量,也不保证下一次一定成功。

p12:construct(p,val) 的规范表达式为 new((void*)p) T(val);用副本构造开始对象生存期。

p13:destroy(p) 的规范表达式为 ((T*)p)->~T();只结束对象生存期。p12–13在这份正式PDF以 Returns 引入,但声明的返回类型确为 void,这里保留其动作含义,不改成返回指针的接口。

20.4.1.2 allocator 全局函数 [lib.allocator.globals]

跳转到“20.4.1.2 allocator 全局函数 [lib.allocator.globals]”
template<class T1, class T2>
bool operator==(const allocator<T1>&, const allocator<T2>&) throw();
template<class T1, class T2>
bool operator!=(const allocator<T1>&, const allocator<T2>&) throw();

p1:== 恒返回 true。p2:!= 恒返回 false。不同 T 的默认分配器也适用,表达的是分配模型的兼容性。

原创安全例(03,静态阅读):

#include <memory>
#include <string>
void one_string() {
std::allocator<std::string> a;
std::string* p = a.allocate(1);
try {
a.construct(p, std::string("hello"));
} catch (...) {
a.deallocate(p, 1);
throw;
}
a.destroy(p);
a.deallocate(p, 1);
}

静态判断:分配失败时没有取得需释放的存储;构造失败时只释放存储,不能析构一个未完成构造的字符串;成功时先析构、再用相同计数归还。这个示例展示单对象分支,不声称可以将其未经修改地用于有多个已构造元素的数组。

20.4.2 原始存储迭代器 [lib.storage.iterator]

跳转到“20.4.2 原始存储迭代器 [lib.storage.iterator]”

来源:03 印刷376–377,PDF404–405;p1–7。

template<class OutputIterator, class T>
class raw_storage_iterator
: public iterator<output_iterator_tag, void, void, void, void> {
public:
explicit raw_storage_iterator(OutputIterator x);
raw_storage_iterator<OutputIterator,T>& operator*();
raw_storage_iterator<OutputIterator,T>& operator=(const T& element);
raw_storage_iterator<OutputIterator,T>& operator++();
raw_storage_iterator<OutputIterator,T> operator++(int);
};

p1:让算法把结果构造进未初始化内存。底层 OutputIterator 须满足输出迭代器要求;其解引用所得对象要能用 operator& 得到 T*。p2:构造后指向 x 所指的位置。p3:operator* 返回 *this。p4–5:赋值运算在当前位置从 element 构造值,返回此适配器的引用。p6:前置递增推进后返回当前迭代器引用。p7:后置递增推进后返回推进前的迭代器值。

要点:这里的 *out = value 在目标未初始化区域执行构造,不能按普通对象的赋值理解。标准没有在本节给任意外部算法增加“失败自动销毁已完成前缀”的普遍保证;若构造抛异常,调用者仍须结合所用算法的合同安排清理。11本节仍没有新增右值赋值重载。

20.4.3 临时缓冲 [lib.temporary.buffer]

跳转到“20.4.3 临时缓冲 [lib.temporary.buffer]”

来源:03 印刷377,PDF405;p1–4。

template<class T>
pair<T*, ptrdiff_t> get_temporary_buffer(ptrdiff_t n);
template<class T>
void return_temporary_buffer(T* p);

p1–2:尝试得到最多容纳 n 个相邻 T 的存储,返回地址与实际容量,容量单位是 sizeof(T),而非字节。无法获得任何存储时返回两个零。实际容量可能小于请求值,不能未经检查就向 first + n 写入。03这里没有11的 noexcept 声明和显式 n <= 0 分支。

p3–4:return_temporary_buffer 释放缓冲;缓冲必须先前由 get_temporary_buffer 分配。它不代替已经开始生存期的对象的析构。不要混用 delete[] 或 free。

20.4.4 未初始化内存算法 [lib.specialized.algorithms]

跳转到“20.4.4 未初始化内存算法 [lib.specialized.algorithms]”

来源:03 印刷377–378,PDF405–406;总则p1。

所有作为模板形参的迭代器,其 operator* 返回的对象都须能以 operator& 取得 T 的指针。uninitialized_copy 的输入迭代器满足输入迭代器要求;目标 ForwardIterator 同时满足前向迭代器与可变迭代器要求。有效目标迭代器的递增、赋值、比较、解引用不得抛异常。这些算法若抛异常,规范要求没有效果;不要把下面展示循环误读成省略清理也合格的完整实现。

20.4.4.1 uninitialized_copy [lib.uninitialized.copy]

跳转到“20.4.4.1 uninitialized_copy [lib.uninitialized.copy]”

p1–2:从 [first,last) 逐个复制构造到 result 开始的原始存储,返回目标范围尾迭代器。

template<class InputIterator, class ForwardIterator>
ForwardIterator uninitialized_copy(InputIterator first, InputIterator last,
ForwardIterator result);
// 原标准的作用表达式,省略异常处理实现细节:
for (; first != last; ++result, ++first)
new (static_cast<void*>(&*result))
typename iterator_traits<ForwardIterator>::value_type(*first);
// Returns: result

20.4.4.2 uninitialized_fill [lib.uninitialized.fill]

跳转到“20.4.4.2 uninitialized_fill [lib.uninitialized.fill]”

p1:在 [first,last) 中从同一个 x 逐个复制构造目标值;返回 void。

template<class ForwardIterator, class T>
void uninitialized_fill(ForwardIterator first, ForwardIterator last, const T& x);
// 原标准作用表达式:
for (; first != last; ++first)
new (static_cast<void*>(&*first))
typename iterator_traits<ForwardIterator>::value_type(x);

20.4.4.3 uninitialized_fill_n [lib.uninitialized.fill.n]

跳转到“20.4.4.3 uninitialized_fill_n [lib.uninitialized.fill.n]”

p1:执行按计数的构造;03签名返回 void。

template<class ForwardIterator, class Size, class T>
void uninitialized_fill_n(ForwardIterator first, Size n, const T& x);
// 原标准作用表达式:
for (; n--; ++first)
new (static_cast<void*>(&*first))
typename iterator_traits<ForwardIterator>::value_type(x);

例中保留正式版的 n-- 条件,不用现代说明把它改成 n > 0 后再声称是03原式。安全调用应提供非负、可表示且不超出实际容量的计数;这里不构造负计数测试或未定义行为探针。

原创安全例(03,静态阅读):

#include <memory>
#include <string>
void three_strings() {
std::allocator<std::string> a;
std::string* p = a.allocate(3);
try {
std::uninitialized_fill_n(p, 3, std::string("x"));
} catch (...) {
// 该算法的异常合同负责消除它的构造效果。
a.deallocate(p, 3);
throw;
}
for (int i = 0; i != 3; ++i) a.destroy(p + i);
a.deallocate(p, 3);
}

静态判断:这里目标是原始存储,不是已有三个字符串的数组;成功后析构恰好三个对象。若使用普通 fill 替代未初始化算法,会把“赋值”施加到尚未开始生存期的对象上,不能这样改。

20.4.5 auto_ptr 类模板 [lib.auto.ptr]

跳转到“20.4.5 auto_ptr 类模板 [lib.auto.ptr]”

来源:03 印刷378–380,PDF406–408;总则p1–3。

p1:保存由 new 得到的对象指针,在自身析构时删除对象。p2:auto_ptr_ref 为转换辅助类,持有对 auto_ptr 的引用,使这种所有权对象可作为函数实参及返回值。其内部表示不是用户应依赖的可移植接口。

namespace std {
template<class Y> struct auto_ptr_ref {};
template<class X> class auto_ptr {
public:
typedef X element_type;
explicit auto_ptr(X* p = 0) throw();
auto_ptr(auto_ptr&) throw();
template<class Y> auto_ptr(auto_ptr<Y>&) throw();
auto_ptr& operator=(auto_ptr&) throw();
template<class Y> auto_ptr& operator=(auto_ptr<Y>&) throw();
auto_ptr& operator=(auto_ptr_ref<X> r) throw();
~auto_ptr() throw();
X& operator*() const throw();
X* operator->() const throw();
X* get() const throw();
X* release() throw();
void reset(X* p = 0) throw();
auto_ptr(auto_ptr_ref<X>) throw();
template<class Y> operator auto_ptr_ref<Y>() throw();
template<class Y> operator auto_ptr<Y>() throw();
};
}

上面 auto_ptr_ref 的空类体是标准概览的呈现,不能据此实现转换协议或假定它无需状态。

p3:严格所有权。复制会复制指针并将所有权转交给目标;多个 auto_ptr 同时拥有同一对象会使程序行为未定义。用途包括动态对象的临时异常安全、把所有权传入函数、从函数返回所有权。重要原注:auto_ptr 不满足标准容器元素的 CopyConstructible 和 Assignable 要求,以它实例化标准容器导致未定义行为。这里保留03的表述,不换成11 unique_ptr 的移动语义结论。

20.4.5.1 auto_ptr 构造与赋值 [lib.auto.ptr.cons]

跳转到“20.4.5.1 auto_ptr 构造与赋值 [lib.auto.ptr.cons]”
编号款接口要求与效果
p1explicit auto_ptr(X* p = 0) throw()后置:持有 p
p2–3auto_ptr(auto_ptr& a) throw()调用 a.release();持有其返回指针,源变空
p4–6template<class Y> auto_ptr(auto_ptr<Y>& a) throw()Y* 能隐式转为 X*;调用 a.release()并持有所得指针
p7–9auto_ptr& operator=(auto_ptr& a) throw()delete get()须良构;执行 reset(a.release());返回 *this
p10–12template<class Y> auto_ptr& operator=(auto_ptr<Y>& a) throw()须能隐式转换指针且 delete get()良构;同样释放源、重置目标;返回 *this
p13–14~auto_ptr() throw()delete get()须良构;执行该删除表达式

从 Derived* 隐式变成 Base* 只证明指针转换可行,不能自动证明通过 Base* 删除派生对象安全。若会经基类执行普通 delete,仍须遵守核心语言对虚析构等的要求;不把转换约束当成删除安全证明。

20.4.5.2 auto_ptr 成员 [lib.auto.ptr.members]

跳转到“20.4.5.2 auto_ptr 成员 [lib.auto.ptr.members]”

p1–2:operator* 要求 get() != 0,返回 *get()。p3:operator-> 返回 get()。p4:get() 返回所持指针,不转交所有权。p5–6:release() 返回原 get(),之后持有空指针,既不析构对象也不释放其存储。p7–8:reset(p) 仅在 get() != p 时执行 delete get(),随后持有 p。这个等值保护属于03 auto_ptr,不能移植推断到11 unique_ptr::reset。

20.4.5.3 auto_ptr 转换 [lib.auto.ptr.conv]

跳转到“20.4.5.3 auto_ptr 转换 [lib.auto.ptr.conv]”

p1–2:从 auto_ptr_ref<X> r 构造时,对 r 所引用的 auto_ptr p 调用 p.release(),然后持有其结果。p3:转为 auto_ptr_ref<Y> 时返回持有 *this 的代理。p4–5:转为 auto_ptr<Y> 时调用 release(),返回持有该结果的目标智能指针。p6–7:代理赋值调用 reset(p.release()),p 是代理引用的源,返回 *this。

原创所有权图与例(03,静态阅读):

复制前: a -> [int 对象] b 为空
b = a: a 为空 b -> [同一个 int 对象]
b 析构: delete 该对象
#include <memory>
void transfer_once() {
std::auto_ptr<int> a(new int(7));
std::auto_ptr<int> b(a);
// 此处 a.get() == 0;b 是唯一所有者。
*b = 8;
}

不要从相同的原始指针再建立第二个所有者,也不要用 auto_ptr<T> 管理 new T[n]。release 之后若不立即转给另一个合适的管理者或正确删除,容易泄漏。11仍有 auto_ptr 的兼容声明,但其规范归附录D.10并被弃用;11第20章的新所有权工具见本册后半。

来源:03 印刷380–381,PDF408–409;p1–6、表33–34。

表号与头文件类别名称
表33 <cstdlib>函数calloc、malloc、free、realloc
表34 <cstring>宏NULL
表34 <cstring>类型size_t
表34 <cstring>函数memchr、memcmp、memcpy、memmove、memset

p1–2:表33所列内容与标准C <stdlib.h> 对应部分相同,但有本节列出的改变。p3:calloc、malloc、realloc 不试图调用 ::operator new() 取得存储。p4:free 不试图调用 ::operator delete() 释放存储。不能通过替换全局 operator new/delete 推断也劫持了所有C分配。

p5–6:表34列出本节涉及的 <cstring> 内容;对应C <string.h>,memchr 有21.4所指定的改变。这里列的是内存部分,不声称是这两个头文件全部内容。03原文两个 SEE ALSO 均打印为 ISO C clause 7.11.2;该交叉引用按底本保留,不暗中改写为另一版C标准的条号。

使用边界(解释):malloc 的原始存储管理不为非平凡C++对象自动执行构造或析构;memcpy 也不是任意C++对象的合法复制构造替代物。合法性须同时满足核心语言的对象、生存期和可复制表示等限制。

第二部分 C++11 内存工具

跳转到“第二部分 C++11 内存工具”

20.6.1 总述 [memory.general]

跳转到“20.6.1 总述 [memory.general]”

来源:11 印刷525,PDF541;p1。此节涵盖 <memory> 及C兼容头 <cstdlib>、<cstring> 的部分内容。

20.6.2 头文件概览 [memory.syn]

跳转到“20.6.2 头文件概览 [memory.syn]”

来源:11 印刷525–529,PDF541–545;p1及总览。<memory> 提供指针属性、容器等使用的分配管理、未初始化区域多对象构造,还声明20.7的智能指针和相关自由函数。

接口组本册完整声明与规则的落点
pointer_traits 主模板与 T* 特化20.6.3
pointer_safety、可达性、无指针区域20.6.4
align20.6.5
allocator_arg_t、allocator_arg20.6.6
uses_allocator20.6.7
allocator_traits20.6.8
allocator、allocator<void>、==、!=20.6.9
raw_storage_iterator20.6.10
临时缓冲的申请与释放20.6.11
addressof、四个未初始化算法20.6.12
default_delete、unique_ptr 单对象和数组特化、关系函数20.7.1
bad_weak_ptr、shared_ptr、weak_ptr、owner_less20.7.2.1–20.7.2.3
shared_ptr 比较、swap、三种转换、get_deleter、流输出20.7.2.2.7–20.7.2.2.11
enable_shared_from_this、shared_ptr 原子自由函数、hash 特化20.7.2.4–20.7.2.6
template<class X> class auto_ptr;总览以 D.10 标为 deprecated;03形态见第一部分

总览没有 make_unique、atomic<shared_ptr<T>>、to_address、is_always_equal 或数组 make_shared,这些不能作为11既有接口添加。

20.6.3 指针 traits [pointer.traits]

跳转到“20.6.3 指针 traits [pointer.traits]”

来源:11 印刷529–530,PDF545–546;总则p1。为指针及仿指针类型的某些属性提供统一入口。下列 see below 是规范占位符,不是可编译C++。

namespace std {
template<class Ptr> struct pointer_traits {
typedef Ptr pointer;
typedef see below element_type;
typedef see below difference_type;
template<class U> using rebind = see below;
static pointer pointer_to(see below r);
};
template<class T> struct pointer_traits<T*> {
typedef T* pointer;
typedef T element_type;
typedef ptrdiff_t difference_type;
template<class U> using rebind = U*;
static pointer pointer_to(see below r) noexcept;
};
}

20.6.3.1 成员类型 [pointer.traits.types]

跳转到“20.6.3.1 成员类型 [pointer.traits.types]”

p1:element_type 优先取 Ptr::element_type。若没有,而 Ptr 是 SomePointer<T, Args> 形式的类模板实例,Args 是零个或多个类型实参,则取第一个类型 T;否则该特化非良构。

p2:difference_type 优先取 Ptr::difference_type,否则为 std::ptrdiff_t。

p3:rebind<U> 优先取 Ptr::rebind<U> 这个类型;否则对上述全类型实参形式,取 SomePointer<U, Args>;不满足这两条时,此 rebind 实例化非良构。注意这里没有 allocator 的 ::other 后缀;不能混淆两种 rebind 协议。含非类型参数的任意指针模板不能自动套进这条回退规则。

20.6.3.2 成员函数 [pointer.traits.functions]

跳转到“20.6.3.2 成员函数 [pointer.traits.functions]”
static pointer pointer_traits::pointer_to(see below r);
static pointer pointer_traits<T*>::pointer_to(see below r) noexcept;

本节备注与返回说明在底本未标编号款。若 element_type 为可带cv的 void,r 的类型未指定;否则底本文字写 T&。泛型入口调用 Ptr::pointer_to(r) 得到一个可解引用、指向 r 的指针;找不到匹配静态成员会使该函数的实例化非良构。原始指针特化返回 std::addressof(r)。这里不把该接口误说成可以凭空制造一个 void&。

20.6.4 指针安全 [util.dynamic.safety]

跳转到“20.6.4 指针安全 [util.dynamic.safety]”

来源:11 印刷530–531,PDF546–547;p1–16、脚注229。该组函数配合3.7.4.3的安全派生指针与实现的指针安全模型;不承诺C++11一定有垃圾回收器。

enum class pointer_safety { relaxed, preferred, strict };
void declare_reachable(void* p);
template<class T> T* undeclare_reachable(T* p);
void declare_no_pointers(char* p, size_t n);
void undeclare_no_pointers(char* p, size_t n);
pointer_safety get_pointer_safety() noexcept;

p1:对同一完整对象,引用它的 declare_reachable 次数多于 undeclare_reachable 次数时,它处于“已声明可达”状态。

p2–4:declare_reachable(p) 要求 p 是安全派生指针或空指针。非空时,所引用的完整对象随后被声明为可达;为记录此状态而额外分配存储失败时可抛 std::bad_alloc。

p5–8:undeclare_reachable(p) 对非空指针要求完整对象以前已被声明可达,并从本次调用至该对象最后一次撤销可达声明保持存活。返回与 p 相等的安全派生副本;不抛异常。注提醒:每个未匹配的可达声明可能占少量额外存储,长时间运行的程序应配对撤销。

p9:declare_no_pointers(p,n) 指定范围中的任何字节都不得已经登记;若该范围属于一个已分配对象,必须全部位于同一个对象内。对象须存活到对应撤销登记;登记其内部区域不应阻止垃圾回收实现回收对象本身。

p10–12:从 p 起的 n 字节不再是可跟踪指针位置,不论这些字节的类型为何。因此,在其中的指针若指向全局 operator new 所创建且未声明可达的对象,就不得解引用。可用来通知垃圾回收器或泄漏检测器不必跟踪该区域。不抛异常;内部记录若需分配而失败,实现可忽略请求。

p13–15:undeclare_no_pointers(p,n) 要求先前登记过完全相同的范围,取消该登记,须在对象生存期结束前调用;不抛异常。

p16:严格指针安全实现返回 pointer_safety::strict;宽松指针安全实现返回 relaxed 还是 preferred 由实现定义。脚注229:preferred 可表示泄漏检测器正在运行,以便程序避免虚假泄漏报告。

静态安全边界:这些函数不延长已被显式析构的C++对象的语言生存期,也不把悬空指针重新变成合法对象指针。声明可达、拥有对象和对象仍存活是三个不同概念。

来源:11 印刷531,PDF547;p1–4。

void* align(std::size_t alignment, std::size_t size,
void*& ptr, std::size_t& space);

p1:若可在 ptr 指向、长度为 space 的缓冲中放下一个满足 alignment 的 size 字节块,就把 ptr 调整到第一个可用地址,并仅按跳过的对齐填充字节数减少 space;不能放下时不改变参数。

p2:alignment 须是基本对齐值或实现在此处支持的扩展对齐值;ptr 须指向至少 space 字节连续存储。p3:失败返回空指针;成功返回调整后的 ptr。p4:更新后的参数便于继续为同一缓冲寻找对齐块。

重要区分:space 不自动扣除 size。分配了这一块的调用者若想继续分配,须自己推进 ptr 并扣除已经占用的对象字节。该函数只计算地址,不构造对象。

原缓冲: [ padding ][ size 字节目标块 ][ 余量 ]
成功后 ptr --------> ^
成功后 space = 原 space - padding
继续使用前再扣 size,并把 ptr 越过目标块

原创安全例(11,静态阅读):

#include <memory>
#include <cstddef>
#include <new>
void aligned_integer() {
alignas(int) unsigned char storage[2 * sizeof(int)];
void* cursor = storage;
std::size_t remaining = sizeof storage;
if (void* slot = std::align(alignof(int), sizeof(int), cursor, remaining)) {
int* p = ::new (slot) int(42);
(void)*p;
cursor = static_cast<unsigned char*>(slot) + sizeof(int);
remaining -= sizeof(int);
}
}

存储具有足够对齐和容量,放置构造建立 int;int 无需显式非平凡析构。例中不存在动态存储释放,也不把 align 成功当成“对象已经构造”的依据。

20.6.6 分配器实参标签 [allocator.tag]

跳转到“20.6.6 分配器实参标签 [allocator.tag]”

来源:11 印刷532,PDF548;p1。

struct allocator_arg_t {};
constexpr allocator_arg_t allocator_arg = allocator_arg_t();

空结构作为独有类型消除构造或函数重载歧义。例如 tuple 有以该标签作为首实参、紧接符合17.6.3.5要求的 allocator 实参的构造函数。标签本身不分配内存。

20.6.7 uses_allocator [allocator.uses]

跳转到“20.6.7 uses_allocator [allocator.uses]”

20.6.7.1 uses_allocator trait [allocator.uses.trait]

跳转到“20.6.7.1 uses_allocator trait [allocator.uses.trait]”

来源:11 印刷532,PDF548;p1。

template<class T, class Alloc> struct uses_allocator;

满足二元类型trait要求。若 T::allocator_type 存在,且 is_convertible<Alloc,T::allocator_type>::value 为真,则派生自 true_type,否则派生自 false_type。可为没有嵌套 allocator_type 的用户定义 T 特化为真,前提是它能用 allocator 构造:构造函数接受前缀 allocator_arg_t, Alloc,或最后一个形参为 Alloc。不能仅因为类型“内部使用内存”就把该trait任意设为真。

20.6.7.2 uses-allocator 构造 [allocator.uses.construction]

跳转到“20.6.7.2 uses-allocator 构造 [allocator.uses.construction]”

来源同上;p1四分支。以 allocator alloc 和 v1...vN 构造 T obj,按以下顺序决定:

优先级条件初始化形式
1trait为假,且 is_constructible<T,V1,...,VN> 为真obj(v1,...,vN)
2trait为真,且前缀形式可构造obj(allocator_arg,alloc,v1,...,vN)
3trait为真,且尾置形式可构造obj(v1,...,vN,alloc)
4以上均不满足请求非良构

前缀形式优先于尾置形式。原注强调:trait为真但具体构造函数不接受 allocator,必须出错,不能静默退回不传 allocator 的构造。

20.6.8 分配器 traits [allocator.traits]

跳转到“20.6.8 分配器 traits [allocator.traits]”

来源:11 印刷532–535,PDF548–551;总则p1。统一分配器接口并为可选成员提供回退;Alloc 仍必须是类类型,不能因traits补全了接口就使用非类分配器。原注指出,因此总能从allocator派生。

template<class Alloc> struct allocator_traits {
typedef Alloc allocator_type;
typedef typename Alloc::value_type value_type;
typedef see below pointer;
typedef see below const_pointer;
typedef see below void_pointer;
typedef see below const_void_pointer;
typedef see below difference_type;
typedef see below size_type;
typedef see below propagate_on_container_copy_assignment;
typedef see below propagate_on_container_move_assignment;
typedef see below propagate_on_container_swap;
template<class T> using rebind_alloc = see below;
template<class T> using rebind_traits = allocator_traits<rebind_alloc<T>>;
static pointer allocate(Alloc& a, size_type n);
static pointer allocate(Alloc& a, size_type n, const_void_pointer hint);
static void deallocate(Alloc& a, pointer p, size_type n);
template<class T, class... Args>
static void construct(Alloc& a, T* p, Args&&... args);
template<class T> static void destroy(Alloc& a, T* p);
static size_type max_size(const Alloc& a);
static Alloc select_on_container_copy_construction(const Alloc& rhs);
};

see below 为规范占位。底本 construct 的 && 字形受损,按可变参数转发接口恢复;不将损字当成新语法。下面单列像素核实的 max_size 声明差别,避免隐藏原版文字。

20.6.8.1 成员类型 [allocator.traits.types]

跳转到“20.6.8.1 成员类型 [allocator.traits.types]”

以下每行保留一个编号款;“优先”均表示对应嵌套类型存在时选它,否则走回退。

款成员优先类型回退
p1pointerAlloc::pointervalue_type*
p2const_pointerAlloc::const_pointerpointer_traits<pointer>::rebind<const value_type>
p3void_pointerAlloc::void_pointerpointer_traits<pointer>::rebind<void>
p4const_void_pointerAlloc::const_void_pointerpointer_traits<pointer>::rebind<const void>
p5difference_typeAlloc::difference_typepointer_traits<pointer>::difference_type
p6size_typeAlloc::size_typemake_unsigned<difference_type>::type
p7propagate_on_container_copy_assignment同名 Alloc 嵌套类型false_type
p8propagate_on_container_move_assignment同名 Alloc 嵌套类型false_type
p9propagate_on_container_swap同名 Alloc 嵌套类型false_type
p10rebind_alloc<T>Alloc::rebind<T>::other若原类型为 Alloc<U,Args> 全类型实参形式,换首实参成 T;否则此别名实例化非良构

注意传播trait的默认值都为假;11本节没有 is_always_equal。rebind_traits<T> 则明确等于 allocator_traits<rebind_alloc<T>>,不另造分配器实例。

20.6.8.2 静态成员函数 [allocator.traits.members]

跳转到“20.6.8.2 静态成员函数 [allocator.traits.members]”

p1:allocate(a,n) 返回 a.allocate(n)。p2:带hint形式若 a.allocate(n,hint) 良构则用它,否则返回 a.allocate(n)。

p3–4:deallocate(a,p,n) 调用 a.deallocate(p,n),不抛异常。traits不免除底层对来源、计数和对象清理的要求。

p5:若 a.construct(p,std::forward<Args>(args)...) 良构,调用它;否则调用 ::new(static_cast<void*>(p)) T(std::forward<Args>(args)...)。该回退负责完美转发,不限于复制构造。

p6:若 a.destroy(p) 良构则调用它,否则执行 p->~T()。

p7:若 a.max_size() 良构,返回其结果;否则返回 numeric_limits<size_type>::max()。这是2011底本的回退值,不能换成后来的除以 sizeof(value_type) 的写法再称原版。另一个已核像素的PDF副本文字差别:概览印刷533写 max_size(const Alloc& a),成员段印刷534写 max_size(Alloc& a)。本册声明概览保留前者,同时记录成员段确有后者,不凭现代实现补正文。

p8:若 rhs.select_on_container_copy_construction() 良构则返回它,否则返回 rhs。这解释了容器复制构造可选取分配器,而不是统一等同于普通分配器复制赋值。

原创静态例(11):

#include <memory>
#include <string>
void one_string_11() {
typedef std::allocator<std::string> A;
typedef std::allocator_traits<A> AT;
A a;
std::string* p = AT::allocate(a, 1);
try {
AT::construct(a, p, 3, 'x');
} catch (...) {
AT::deallocate(a, p, 1);
throw;
}
AT::destroy(a, p);
AT::deallocate(a, p, 1);
}

构造实参 (3,'x') 转发给字符串构造函数。traits选择成员或回退不改变“成功后恰好析构一次,最后以匹配参数归还”的责任。

20.6.9 默认分配器 [default.allocator]

跳转到“20.6.9 默认分配器 [default.allocator]”

来源:11 印刷535–537,PDF551–553。与03相比,保留既有类型成员、rebind 和 allocator<void>;构造、地址及大小查询使用 noexcept;construct 变为可变参数、可构造 U,destroy 也以 U 为模板参数。概览没有给析构函数显式写 noexcept,本册不在转录中擅加。

namespace std {
template<class T> class allocator;
template<> class allocator<void> {
public:
typedef void* pointer;
typedef const void* const_pointer;
typedef void value_type;
template<class U> struct rebind { typedef allocator<U> other; };
};
template<class T> class allocator {
public:
typedef size_t size_type;
typedef ptrdiff_t difference_type;
typedef T* pointer;
typedef const T* const_pointer;
typedef T& reference;
typedef const T& const_reference;
typedef T value_type;
template<class U> struct rebind { typedef allocator<U> other; };
allocator() noexcept;
allocator(const allocator&) noexcept;
template<class U> allocator(const allocator<U>&) noexcept;
~allocator();
pointer address(reference x) const noexcept;
const_pointer address(const_reference x) const noexcept;
pointer allocate(size_type, allocator<void>::const_pointer hint = 0);
void deallocate(pointer p, size_type n);
size_type max_size() const noexcept;
template<class U, class... Args> void construct(U* p, Args&&... args);
template<class U> void destroy(U* p);
};
}

20.6.9.1 allocator 成员 [allocator.members]

跳转到“20.6.9.1 allocator 成员 [allocator.members]”

p1:除析构函数外,不同线程并发调用默认分配器成员不得因这些调用引入数据竞争。对某一存储单元的分配、释放调用形成单一全序,每次释放发生先于该序中下一次分配(若有)。这不是允许多个线程无同步地读写同一用户对象。

p2–3:两种 address 都返回 x 所引用对象的真实地址,即使重载了 operator&。与03仅写 &x 的文字分开记录。

p4–7:allocate(n,hint) 返回大小为 n*sizeof(T)、为 T 适当对齐的存储数组首元素地址。是否支持过度对齐类型由实现定义。相邻容器元素地址可用作hint只是注;利用hint方式、调用 ::operator new(std::size_t) 的时机次数未指定。无法取得存储抛 bad_alloc。

p8–10:deallocate(p,n) 要求 p 是由 allocate() 获得的值,n 与该次请求一致;释放其存储,使用 ::operator delete(void*),调用时机未指定。

p11:max_size() 返回 allocate(N,0) 可能成功的最大 N。

p12:construct(U* p,Args&&... args) 执行 ::new((void*)p) U(std::forward<Args>(args)...)。p13:destroy(U* p) 执行 p->~U()。对象类型可以是不同于allocator自身 value_type 的 U,但存储必须足够、对齐和生存期安排必须正确。

20.6.9.2 allocator 全局函数 [allocator.globals]

跳转到“20.6.9.2 allocator 全局函数 [allocator.globals]”
template<class T1, class T2>
bool operator==(const allocator<T1>&, const allocator<T2>&) noexcept;
template<class T1, class T2>
bool operator!=(const allocator<T1>&, const allocator<T2>&) noexcept;

p1:相等比较恒真。p2:不等比较恒假。保留了跨元素类型的可互换默认分配模型。

20.6.10 原始存储迭代器 [storage.iterator]

跳转到“20.6.10 原始存储迭代器 [storage.iterator]”

来源:11 印刷537,PDF553;p1–7。

template<class OutputIterator, class T>
class raw_storage_iterator
: public iterator<output_iterator_tag, void, void, void, void> {
public:
explicit raw_storage_iterator(OutputIterator x);
raw_storage_iterator<OutputIterator,T>& operator*();
raw_storage_iterator<OutputIterator,T>& operator=(const T& element);
raw_storage_iterator<OutputIterator,T>& operator++();
raw_storage_iterator<OutputIterator,T> operator++(int);
};

p1:将算法结果构造进未初始化内存;底层为输出迭代器,解引用对象须能取址成 T*。p2:构造后与 x 指向同一位置。p3:解引用返回 *this。p4–5:从 element 在当前位置构造值,返回适配器引用。p6:前置递增推进并返回自身引用。p7:后置递增推进并返回旧值。11这一版本仍只有 const T& 赋值,不把后来版本的移动构造支持加入本节。

20.6.11 临时缓冲 [temporary.buffer]

跳转到“20.6.11 临时缓冲 [temporary.buffer]”

来源:11 印刷537–538,PDF553–554;p1–4。

template<class T>
pair<T*, ptrdiff_t> get_temporary_buffer(ptrdiff_t n) noexcept;
template<class T> void return_temporary_buffer(T* p);

p1:取得可容纳最多 n 个相邻 T 的原始存储;是否支持过度对齐类型由实现定义。p2:返回地址及以 sizeof(T) 为单位的容量;无法得到存储或 n <= 0 时返回两个零。p3:释放 p 指向的缓冲。p4:缓冲须以前由 get_temporary_buffer 分配。归还前仍应先结束其中已经成功构造的对象生存期。

20.6.12 特殊算法 [specialized.algorithms]

跳转到“20.6.12 特殊算法 [specialized.algorithms]”

来源:11 印刷538–539,PDF554–555;总则p1。迭代器解引用对象须能用 operator& 得到 T 的指针;uninitialized_copy 输入满足输入迭代器要求。目标满足前向迭代器要求;有效目标迭代器的递增、赋值、比较、解引用不得抛异常。若算法抛异常,则没有效果。不要据循环省略异常清理,也不要用C++17以后采用 addressof 的算法措辞替换本版 &* 表达式。

20.6.12.1 addressof [specialized.addressof]

跳转到“20.6.12.1 addressof [specialized.addressof]”
template<class T> T* addressof(T& r) noexcept;

p1:返回 r 所引用对象或函数的真实地址,即使 operator& 被重载。本版未把它声明为 constexpr。

20.6.12.2 uninitialized_copy [uninitialized.copy]

跳转到“20.6.12.2 uninitialized_copy [uninitialized.copy]”

p1–2:范围版从 [first,last) 复制构造到目标原始存储,返回目标尾迭代器。p3–4:计数版只在 n > 0 时继续构造,返回推进后的 result。以下保留正式版作用式的 ::new 和 &*。

转录说明:用户提供的11 PDF印刷538(PDF554)中,uninitialized_copy_n 的循环开头可见左花括号,而在p4返回说明前未见相应右花括号。下面的 } 是为完整呈现循环结构而补齐的排版恢复,不声称这一字符在该副本页图可见,也不据此判断ISO原始出版物错误。

template<class InputIterator, class ForwardIterator>
ForwardIterator uninitialized_copy(InputIterator first, InputIterator last,
ForwardIterator result);
// p1作用式
for (; first != last; ++result, ++first)
::new (static_cast<void*>(&*result))
typename iterator_traits<ForwardIterator>::value_type(*first);
// p2返回 result
template<class InputIterator, class Size, class ForwardIterator>
ForwardIterator uninitialized_copy_n(InputIterator first, Size n,
ForwardIterator result);
// p3作用式
for (; n > 0; ++result, ++first, --n) {
::new (static_cast<void*>(&*result))
typename iterator_traits<ForwardIterator>::value_type(*first);
}
// p4返回 result

20.6.12.3 uninitialized_fill [uninitialized.fill]

跳转到“20.6.12.3 uninitialized_fill [uninitialized.fill]”

p1:用 x 复制构造 [first,last) 中的每个目标对象,返回 void。

template<class ForwardIterator, class T>
void uninitialized_fill(ForwardIterator first, ForwardIterator last, const T& x);
for (; first != last; ++first)
::new (static_cast<void*>(&*first))
typename iterator_traits<ForwardIterator>::value_type(x);

20.6.12.4 uninitialized_fill_n [uninitialized.fill.n]

跳转到“20.6.12.4 uninitialized_fill_n [uninitialized.fill.n]”

p1:计数构造后返回尾迭代器;这是与03返回 void 的显著差别。原式循环条件仍为 n--,安全调用使用非负且适合目标容量的计数。

template<class ForwardIterator, class Size, class T>
ForwardIterator uninitialized_fill_n(ForwardIterator first, Size n, const T& x);
for (; n--; ++first)
::new (static_cast<void*>(&*first))
typename iterator_traits<ForwardIterator>::value_type(x);
return first;

来源:11 印刷539–540,PDF555–556;p1–7、表45–46。

表头文件分类与全部列名
45<cstdlib>函数 calloc、malloc、free、realloc
46<cstring>宏 NULL;类型 size_t;函数 memchr、memcmp、memcpy、memmove、memset

p1–4:表45的C分配内容与标准C <stdlib.h> 相同,但 calloc、malloc、realloc 不借 ::operator new() 分配,free 不借 ::operator delete() 释放。

p5:由 malloc、calloc、realloc 直接分配的存储,在分配时隐式声明可达,释放时不再声明可达;调用 undeclare_reachable() 不必取消这种状态。原注解释这能让既有C库不受“非安全派生指针”的限制,也容许独立分配区域,不过可用的垃圾回收、泄漏检测选项更少。不能故意把这些C分配函数当成 declare_reachable 的替身;新代码被强烈建议按 operator new 所分配存储那样谨慎处理这些内存。

p6–7:表46对应 <string.h> 的内存内容,memchr 的改变见21.7。此处两个 SEE ALSO 在底本均写 ISO C Clause 7.11.2,本册保留来源,不把另一版C标准编号嫁接过来。

第三部分 C++11 智能指针

跳转到“第三部分 C++11 智能指针”

来源:11 印刷540–566,PDF556–582。所有权是对象清理责任的归属;指针值是访问地址;两者在别名构造等情况下不同。下面先讲严格独占,再讲共享、弱引用及原子自由函数。

20.7.1 unique_ptr 类模板 [unique.ptr]

跳转到“20.7.1 unique_ptr 类模板 [unique.ptr]”

来源:11 印刷540–541,PDF556–557;p1–6。

p1:独占指针对象 u 保存指向另一对象 p 的指针,并在 u 析构时处置 p;称为拥有它。p2:执行处置的函数对象是相关删除器,正确调用要按该策略适当释放资源,不一定只能用普通 delete。

p3:重置所持指针和删除器前,旧对象必须通过旧删除器得到正确处置。p4:把所有权转给 u2 后,u2 的指针等于转移前 u 的指针,u 的指针为空;若原删除器有状态,该状态转给目标。目标原有资源也须先通过原删除器正确处置。原注:转移过程中删除器状态不必复制,可以移动或交换。

p5:类型支持 MoveConstructible、MoveAssignable,不支持 CopyConstructible、CopyAssignable;T 可以是不完整类型。后者不代表在执行默认删除时也可不完整。p6注:用于动态资源异常安全、传入和返回所有权。

template<class T> struct default_delete;
template<class T> struct default_delete<T[]>;
template<class T, class D = default_delete<T>> class unique_ptr;
template<class T, class D> class unique_ptr<T[], D>;

20.7.1.1 默认删除器 [unique.ptr.dltr]

跳转到“20.7.1.1 默认删除器 [unique.ptr.dltr]”

20.7.1.1.1 总述 [unique.ptr.dltr.general]

跳转到“20.7.1.1.1 总述 [unique.ptr.dltr.general]”

p1–2:default_delete 是 unique_ptr 的默认销毁策略,模板参数 T 可不完整。声明或保存该删除器,与实际调用删除操作有不同完整性时点要求。

20.7.1.1.2 default_delete [unique.ptr.dltr.dft]

跳转到“20.7.1.1.2 default_delete [unique.ptr.dltr.dft]”

来源:11 印刷541–542,PDF557–558。

template<class T> struct default_delete {
constexpr default_delete() noexcept = default;
template<class U> default_delete(const default_delete<U>& other) noexcept;
void operator()(T* ptr) const;
};

p1–2:转换构造从另一个删除器建立对象;仅在 U* 可隐式转换为 T* 时参与重载决议。p3–4:调用运算执行 delete ptr;此时 T 不完整则程序非良构。

20.7.1.1.3 default_delete 数组特化 [unique.ptr.dltr.dft1]

跳转到“20.7.1.1.3 default_delete 数组特化 [unique.ptr.dltr.dft1]”

来源:11 印刷542,PDF558。

template<class T> struct default_delete<T[]> {
constexpr default_delete() noexcept = default;
void operator()(T*) const;
template<class U> void operator()(U*) const = delete;
};

p1–2:operator()(T* ptr) 执行 delete[] ptr;T 不完整则程序非良构。2011原版这个特化没有现代形式的转换构造,且明确删除 operator()(U*);不要把后来放宽的数组转换规则倒填进本版。

20.7.1.2 单对象 unique_ptr [unique.ptr.single]

跳转到“20.7.1.2 单对象 unique_ptr [unique.ptr.single]”

来源:11 印刷542–547,PDF558–563;总则p1–4及五个子节。

template<class T, class D = default_delete<T>> class unique_ptr {
public:
typedef see below pointer;
typedef T element_type;
typedef D deleter_type;
constexpr unique_ptr() noexcept;
explicit unique_ptr(pointer p) noexcept;
unique_ptr(pointer p, see below d1) noexcept;
unique_ptr(pointer p, see below d2) noexcept;
unique_ptr(unique_ptr&& u) noexcept;
constexpr unique_ptr(nullptr_t) noexcept : unique_ptr() {}
template<class U, class E> unique_ptr(unique_ptr<U,E>&& u) noexcept;
template<class U> unique_ptr(auto_ptr<U>&& u) noexcept;
~unique_ptr();
unique_ptr& operator=(unique_ptr&& u) noexcept;
template<class U, class E>
unique_ptr& operator=(unique_ptr<U,E>&& u) noexcept;
unique_ptr& operator=(nullptr_t) noexcept;
typename add_lvalue_reference<T>::type operator*() const;
pointer operator->() const noexcept;
pointer get() const noexcept;
deleter_type& get_deleter() noexcept;
const deleter_type& get_deleter() const noexcept;
explicit operator bool() const noexcept;
pointer release() noexcept;
void reset(pointer p = pointer()) noexcept;
void swap(unique_ptr& u) noexcept;
unique_ptr(const unique_ptr&) = delete;
unique_ptr& operator=(const unique_ptr&) = delete;
};

p1:自定义删除器 D 须是函数对象类型、函数的左值引用或函数对象的左值引用;对 D 的值 d 和 pointer 的值 ptr,d(ptr) 须合法并按该删除器的策略适当处置。p2:非引用删除器须满足 Destructible。

p3:若 remove_reference<D>::type::pointer 存在,pointer 取它;否则取 T*。该类型须满足 NullablePointer。因此独占指针可以保存符合条件的非原始指针。p4原例:设 A = allocator_traits<X>,则 A::pointer、A::const_pointer、A::void_pointer、A::const_void_pointer 可用作其 pointer 类型;这并不自动提供匹配的删除策略。

20.7.1.2.1 unique_ptr 构造 [unique.ptr.single.ctor]

跳转到“20.7.1.2.1 unique_ptr 构造 [unique.ptr.single.ctor]”

p1–4:默认构造要求 D 可默认构造且此构造不抛异常;对指针和删除器做值初始化,不拥有对象;后置 get() == nullptr,get_deleter() 引用内部删除器。以指针类型或引用类型作为 D 实例化这个构造函数,程序非良构。

p5–8:只给 pointer p 的构造同样要求不抛的默认构造删除器,保存 p 并值初始化删除器;后置 get() == p。D 是指针或引用类型时也非良构。因此函数指针删除器常须明确传入可调用函数值,而不是指望默认的空函数指针删除资源。

p9–11:两个显式传删除器的构造,其形参取决于 D:

D 的形式第一种签名形参第二种签名形参
非引用 Apointer p, const A& dpointer p, A&& d
A&pointer p, A& dpointer p, A&& d
const A&pointer p, const A& dpointer p, const A&& d

这三行展开说明中的原文签名省略 noexcept,外层正式构造声明仍标有 noexcept。

p12:非引用删除器下,左值或const右值选第一种,要求删除器可复制且复制不抛,保存其副本;非const右值选第二种,要求可移动且移动不抛。若 D 是左值引用,实参须引用兼容;绑定右值的第二种导致程序非良构,避免把引用删除器绑定到临时对象。绑定左值时引用的类型不必可复制或可移动,存的是引用。D 不能是右值引用类型。

p13–14:保存 p 并按以上规则初始化删除器;后置 get()==p;引用删除器的 get_deleter() 引用传入左值。重要原例静态摘录(最后一行明确为应诊断的错误,不执行):

D d;
unique_ptr<int,D> p1(new int, D()); // D须可移动构造
unique_ptr<int,D> p2(new int, d); // D须可复制构造
unique_ptr<int,D&> p3(new int, d); // 保存对d的引用
unique_ptr<int,const D&> p4(new int, D()); // 错误:引用删除器配临时对象

p15–17:同型移动构造要求非引用 D 可移动构造;从 D 右值构造删除器不得抛异常。将所有权从 u 转到目标;若 D 为引用类型,复制的是删除器引用,否则移动构造删除器。结果的指针等于源原指针,get_deleter() 引用由源构造的内部删除器;引用形式的两边继续引用同一左值。源变空来自20.7.1总则的转移合同。原注建议可用 std::forward<D> 实现删除器构造。

p18–21:跨类型移动构造从 unique_ptr<U,E>&& 转入。删除器从非引用 E 的右值或引用 E 的左值构造,须良构且不抛。只在三个条件都满足时参与重载:源 pointer 隐式转为目标 pointer;U 不是数组;若 D 为引用则 E 与 D 同型,否则 E 隐式转为 D。转移指针和相应删除器状态,结果保存源原指针。原注用 std::forward<E> 解释相应删除器构造。

p22–24:从 auto_ptr<U>&& 转入时保存 u.release(),值初始化删除器;后置源为空,目标保存源原指针。仅当 U* 隐式转为 T* 且 D 为 default_delete<T> 时参与重载。这是11从旧所有权工具迁移的桥接接口,不是继续鼓励 auto_ptr 容器化。

20.7.1.2.2 unique_ptr 析构 [unique.ptr.single.dtor]

跳转到“20.7.1.2.2 unique_ptr 析构 [unique.ptr.single.dtor]”

p1:get_deleter()(get()) 须良构、具有良定义行为且不抛异常;默认删除器要求 T 完整。p2:空时没有效果;非空时调用此删除器表达式。空智能指针并不意味着必须调用删除器处理空值。

20.7.1.2.3 unique_ptr 赋值 [unique.ptr.single.asgn]

跳转到“20.7.1.2.3 unique_ptr 赋值 [unique.ptr.single.asgn]”

p1–3:同型移动赋值,非引用删除器须可移动赋值且从右值赋值不抛;引用删除器所引用类型须可复制赋值且从左值赋值不抛。效果如先 reset(u.release()),再从 std::forward<D>(u.get_deleter()) 赋值删除器;返回 *this。引用删除器赋值会赋值到所引用对象,不是让引用重新绑定。

p4–7:跨类型移动赋值要求从对应右值或左值 E 赋值删除器良构且不抛;仅当源指针能隐式转为目标指针且 U 非数组时参与重载。先释放源并重置目标,再赋值删除器;返回 *this。用户提供的2011 PDF副本中,本款p6可见文字写 std::forward<D>(u.get_deleter()),与该构造函数p20的 forward<E> 不同,本册不自行修成后来的措辞。

p8–10:赋 nullptr 等效 reset(),后置为空,返回 *this。

20.7.1.2.4 unique_ptr 观察器 [unique.ptr.single.observers]

跳转到“20.7.1.2.4 unique_ptr 观察器 [unique.ptr.single.observers]”

p1–2:operator* 要求非空,返回 *get();返回类型为 add_lvalue_reference<T>::type。p3–5:operator-> 也要求非空,返回 get();通常其使用需要 T 完整。p6:get() 返回存储指针。p7:const及非const get_deleter() 返回存储删除器的相应引用。p8:显式布尔转换返回 get()!=nullptr。访问对象不会转移所有权。

20.7.1.2.5 unique_ptr 修改器 [unique.ptr.single.modifiers]

跳转到“20.7.1.2.5 unique_ptr 修改器 [unique.ptr.single.modifiers]”

p1–2:release() 后对象变空,返回调用开始时的存储指针;不会调用删除器。

p3–5:reset(p) 要求调用删除器良构、良定义且不抛。先把存储指针改成 p,然后旧指针非空时调用删除器处置旧值;后置 get()==p。原注强调顺序重要,因为删除器可能销毁 *this;若真这样做,后置表达式已经不能求值。这条先写新指针的顺序不能颠倒。

p6–7:swap(u) 要求删除器可交换且交换不抛;交换双方指针及删除器。

安全提醒:p.reset(p.get()) 不等于 auto_ptr 的等值保护;本节没有跳过相同非空指针的规则。正确放弃并接回同一对象的讨论要依据具体接口顺序,但普通代码不应通过自我reset来表达“什么都不做”。

原创安全例(11,静态阅读):

#include <memory>
#include <utility>
struct Item { int value; explicit Item(int n) : value(n) {} };
void take(std::unique_ptr<Item> item) {
if (item) item->value += 1;
}
void transfer_11() {
std::unique_ptr<Item> p(new Item(4));
take(std::move(p));
// 函数返回后p为空;对象由take的参数在离开时销毁。
}

std::move 本身只提供可移动的表达式,实际所有权转移由参数的移动构造完成。未使用11不存在的 make_unique。

20.7.1.3 运行期长度数组的 unique_ptr [unique.ptr.runtime]

跳转到“20.7.1.3 运行期长度数组的 unique_ptr [unique.ptr.runtime]”

来源:11 印刷547–549,PDF563–565;p1–3。

template<class T, class D> class unique_ptr<T[],D> {
public:
typedef see below pointer;
typedef T element_type;
typedef D deleter_type;
constexpr unique_ptr() noexcept;
explicit unique_ptr(pointer p) noexcept;
unique_ptr(pointer p, see below d) noexcept;
unique_ptr(pointer p, see below d) noexcept;
unique_ptr(unique_ptr&& u) noexcept;
constexpr unique_ptr(nullptr_t) : unique_ptr() {}
~unique_ptr();
unique_ptr& operator=(unique_ptr&& u) noexcept;
unique_ptr& operator=(nullptr_t) noexcept;
T& operator[](size_t i) const;
pointer get() const noexcept;
deleter_type& get_deleter() noexcept;
const deleter_type& get_deleter() const noexcept;
explicit operator bool() const noexcept;
pointer release() noexcept;
void reset(pointer p = pointer()) noexcept;
void reset(nullptr_t) noexcept;
template<class U> void reset(U) = delete;
void swap(unique_ptr& u) noexcept;
unique_ptr(const unique_ptr&) = delete;
unique_ptr& operator=(const unique_ptr&) = delete;
};

概览的 nullptr_t 委托构造在本版未显式写 noexcept,此处按原声明保留。

p1逐项:不同类型的 unique_ptr<T[],D> 之间,及数组形式与非数组形式之间的转换,会使程序非良构;构造和reset拒绝派生自 T 的类型指针;没有 operator*、operator->;提供 operator[];默认删除器用 delete[]。p2:只另述与主模板不同的行为,其余沿用主模板。p3:模板实参 T 必须是完整类型。这是2011数组特化原文,不能将主模板允许不完整类型的总则不加区分地套到这里。

20.7.1.3.1 数组构造 [unique.ptr.runtime.ctor]

跳转到“20.7.1.3.1 数组构造 [unique.ptr.runtime.ctor]”

此段无编号款。带 pointer 的三种构造与主模板相同,但不接受只是能转换为 pointer 的其他指针类型;注给出可用私有模板重载实现拒绝。这一原版限制比现代已修订的数组转换规则严格。

20.7.1.3.2 数组观察器 [unique.ptr.runtime.observers]

跳转到“20.7.1.3.2 数组观察器 [unique.ptr.runtime.observers]”

p1–2:operator[](i) 要求 i 小于所指数组的元素数,返回 get()[i]。该智能指针没有记录或查询数组长度的标准接口,也不承诺运行期越界检查。

20.7.1.3.3 数组修改器 [unique.ptr.runtime.modifiers]

跳转到“20.7.1.3.3 数组修改器 [unique.ptr.runtime.modifiers]”

p1–2:reset(pointer p=pointer()) 与 reset(nullptr_t p) 的成员段对旧值规定:若 get()==nullptr 没有处置效果,否则调用 get_deleter()(get());后置 get()==p。本段未像单对象版本展开“先存后删”的完整顺序,按本版独立文字记录,不用之后标准的统一说明覆写。模板 reset(U)=delete 阻止不受支持的指针转换。

#include <memory>
void array_11() {
std::unique_ptr<int[]> a(new int[3]());
a[0] = 1;
a[1] = 2;
a[2] = 3;
} // 默认策略匹配delete[]

这是原创静态安全例;数组长度由程序自身掌握。不能用 unique_ptr<int> 接管 new int[3]。

20.7.1.4 unique_ptr 专用算法与比较 [unique.ptr.special]

跳转到“20.7.1.4 unique_ptr 专用算法与比较 [unique.ptr.special]”

来源:11 印刷549–550,PDF565–566;p1–16。

template<class T, class D>
void swap(unique_ptr<T,D>& x, unique_ptr<T,D>& y) noexcept;
template<class T1, class D1, class T2, class D2>
bool operator==(const unique_ptr<T1,D1>& x, const unique_ptr<T2,D2>& y);
template<class T1, class D1, class T2, class D2>
bool operator!=(const unique_ptr<T1,D1>& x, const unique_ptr<T2,D2>& y);
template<class T1, class D1, class T2, class D2>
bool operator<(const unique_ptr<T1,D1>& x, const unique_ptr<T2,D2>& y);
template<class T1, class D1, class T2, class D2>
bool operator<=(const unique_ptr<T1,D1>& x, const unique_ptr<T2,D2>& y);
template<class T1, class D1, class T2, class D2>
bool operator>(const unique_ptr<T1,D1>& x, const unique_ptr<T2,D2>& y);
template<class T1, class D1, class T2, class D2>
bool operator>=(const unique_ptr<T1,D1>& x, const unique_ptr<T2,D2>& y);
template<class T, class D> bool operator==(const unique_ptr<T,D>& x, nullptr_t) noexcept;
template<class T, class D> bool operator==(nullptr_t, const unique_ptr<T,D>& x) noexcept;
template<class T, class D> bool operator!=(const unique_ptr<T,D>& x, nullptr_t) noexcept;
template<class T, class D> bool operator!=(nullptr_t, const unique_ptr<T,D>& x) noexcept;
template<class T, class D> bool operator<(const unique_ptr<T,D>& x, nullptr_t);
template<class T, class D> bool operator<(nullptr_t, const unique_ptr<T,D>& x);
template<class T, class D> bool operator>(const unique_ptr<T,D>& x, nullptr_t);
template<class T, class D> bool operator>(nullptr_t, const unique_ptr<T,D>& x);
template<class T, class D> bool operator<=(const unique_ptr<T,D>& x, nullptr_t);
template<class T, class D> bool operator<=(nullptr_t, const unique_ptr<T,D>& x);
template<class T, class D> bool operator>=(const unique_ptr<T,D>& x, nullptr_t);
template<class T, class D> bool operator>=(nullptr_t, const unique_ptr<T,D>& x);

p1:自由 swap 调用 x.swap(y)。p2–3:==、!= 比较 get() 值,不比较被指对象或删除器。

p4–6:令 CT 为两种 pointer 的 common_type::type。less<CT> 须是能在指针值上建立严格弱序的函数对象;< 返回 less<CT>()(x.get(),y.get())。任一指针类型不能隐式转为 CT 则程序非良构。

p7–9:x<=y 返回 !(y<x);x>y 返回 y<x;x>=y 返回 !(x<y)。

p10–11:与 nullptr 的两侧相等都返回 !x,不等都返回 (bool)x。

p12–13:与 nullptr 的 < 要求 less<unique_ptr<T,D>::pointer> 对指针值建立严格弱序;分别比较 (x.get(),nullptr) 与 (nullptr,x.get())。

p14:x>nullptr 返回 nullptr<x,nullptr>x 返回 x<nullptr。p15:两侧 <= 分别为 !(nullptr<x)、!(x<nullptr)。p16:两侧 >= 分别为 !(x<nullptr)、!(nullptr<x)。这些是指针序关系,不是资源值大小,也不能由整数地址经验推断任意顺序。

20.7.2 共享所有权指针 [util.smartptr]

跳转到“20.7.2 共享所有权指针 [util.smartptr]”

共享所有权使多个句柄共同承担对象清理责任;弱引用能够记住这组所有权而不延长对象的共享拥有期。比较“存储地址”和比较“所有权组”是两套不同的关系。

20.7.2.1 bad_weak_ptr [util.smartptr.weakptr]

跳转到“20.7.2.1 bad_weak_ptr [util.smartptr.weakptr]”

来源:11 印刷550–551,PDF566–567;p1–2。

class bad_weak_ptr : public std::exception {
public:
bad_weak_ptr() noexcept;
};

p1:从 weak_ptr 构造 shared_ptr 时会抛此异常(触发条件见构造条款的已过期情形)。p2:默认构造后,what() 返回 "bad_weak_ptr"。这是2011版明确字符串,不改写为后续标准的实现定义说明。

20.7.2.2 shared_ptr 类模板 [util.smartptr.shared]

跳转到“20.7.2.2 shared_ptr 类模板 [util.smartptr.shared]”

来源:11 印刷551–553,PDF567–569;总则p1–4。

p1:保存通常来自 new 的指针,最后剩余的所有者负责销毁对象或按策略释放资源。不拥有指针的 shared_ptr 称为空。这个“空”按拥有关系定义,不等同于 get()==0,别名构造会暴露二者差别。

template<class T> class shared_ptr {
public:
typedef T element_type;
constexpr shared_ptr() noexcept;
template<class Y> explicit shared_ptr(Y* p);
template<class Y, class D> shared_ptr(Y* p, D d);
template<class Y, class D, class A> shared_ptr(Y* p, D d, A a);
template<class D> shared_ptr(nullptr_t p, D d);
template<class D, class A> shared_ptr(nullptr_t p, D d, A a);
template<class Y> shared_ptr(const shared_ptr<Y>& r, T* p) noexcept;
shared_ptr(const shared_ptr& r) noexcept;
template<class Y> shared_ptr(const shared_ptr<Y>& r) noexcept;
shared_ptr(shared_ptr&& r) noexcept;
template<class Y> shared_ptr(shared_ptr<Y>&& r) noexcept;
template<class Y> explicit shared_ptr(const weak_ptr<Y>& r);
template<class Y> shared_ptr(auto_ptr<Y>&& r);
template<class Y, class D> shared_ptr(unique_ptr<Y,D>&& r);
constexpr shared_ptr(nullptr_t) : shared_ptr() {}
~shared_ptr();
shared_ptr& operator=(const shared_ptr& r) noexcept;
template<class Y> shared_ptr& operator=(const shared_ptr<Y>& r) noexcept;
shared_ptr& operator=(shared_ptr&& r) noexcept;
template<class Y> shared_ptr& operator=(shared_ptr<Y>&& r) noexcept;
template<class Y> shared_ptr& operator=(auto_ptr<Y>&& r);
template<class Y, class D> shared_ptr& operator=(unique_ptr<Y,D>&& r);
void swap(shared_ptr& r) noexcept;
void reset() noexcept;
template<class Y> void reset(Y* p);
template<class Y, class D> void reset(Y* p, D d);
template<class Y, class D, class A> void reset(Y* p, D d, A a);
T* get() const noexcept;
T& operator*() const noexcept;
T* operator->() const noexcept;
long use_count() const noexcept;
bool unique() const noexcept;
explicit operator bool() const noexcept;
template<class U> bool owner_before(shared_ptr<U> const& b) const;
template<class U> bool owner_before(weak_ptr<U> const& b) const;
};

T& 的 void 特例见观察器,不能仅按概览认定 shared_ptr<void> 必不合法。nullptr_t 委托构造按11原概览不额外补写 noexcept。

p2:特化须可复制构造、可复制赋值、可小于比较,因而能用作标准容器元素;能用于布尔条件;T 可不完整。p3原例展示在条件声明中使用 dynamic_pointer_cast<X>(py) 得到的 shared_ptr<X>,转换成功才进入分支。

p4:判断数据竞争时,这些成员只访问或修改 shared_ptr、weak_ptr 对象本身,不访问其所引用对象;use_count() 变化不视为可能引入数据竞争的对象修改。解释:不同句柄共享同一所有权组的计数管理,不给被指对象提供自动同步;同一个句柄的并发写仍须遵守同步规则,专用原子自由函数见20.7.2.5。

20.7.2.2.1 shared_ptr 构造 [util.smartptr.shared.const]

跳转到“20.7.2.2.1 shared_ptr 构造 [util.smartptr.shared.const]”

来源:11 印刷553–555,PDF569–571;p1–34。

p1–2:默认构造空句柄,后置 use_count()==0 && get()==0。

p3–7:从 Y* p 构造要求可转为 T*,Y 完整,delete p 良构、有良定义行为且不抛异常。目标拥有 p,后置计数为1且保存 p。分配内存失败抛 bad_alloc;无法取得其他资源可抛实现定义异常。构造失败会调用 delete p。因此本构造已接管原始指针的失败清理,不应在外层再重复删除同一对象。

p8–12:四种自定义删除器构造接受 Y* 或 nullptr_t,可另带allocator。要求 p 可转为 T*;D 可复制构造,其复制与析构不抛;d(p) 良构、有良定义行为且不抛。A 是allocator,其复制与析构不抛。保存 p 和删除器;带allocator的两种用其副本为内部用途分配内存。后置计数为1且 get()==p;失败可能抛 bad_alloc 或其他资源对应的实现定义异常,并调用 d(p) 清理。

解释:shared_ptr<T>(nullptr,d) 可以有 get()==nullptr、布尔值假而 use_count()==1,且最后释放会按删除器策略处理这个空值。这与默认构造空句柄不同。

p13–16:别名构造 shared_ptr(const shared_ptr<Y>& r,T* p) 保存 p,但与 r 共享所有权;后置 get()==p、计数等于 r.use_count()。用户须确保 p 至少在这组所有权销毁前保持有效,以免出现悬空指针。原注特意允许“没有拥有关系但存储指针非空”的句柄,即源拥有关系为空时的别名构造。

p17–19:复制构造,异型版本只在 Y* 隐式转为 T* 时参与重载;源无拥有关系时目标也无,源有则共享。后置存储指针相同、计数相同。保留源的别名地址,不重新创建原始指针的控制关系。

p20–22:移动构造,异型版本只在 Y* 能转为 T* 时参与重载。目标取得源旧值;源无拥有关系且 r.get()==0。

p23–27:从 weak_ptr<Y> 显式构造要求 Y* 能转为 T*;与源共享所有权并复制其存储指针,后置计数相同;若 r.expired() 抛 bad_weak_ptr;异常时构造无效果。

p28–32:从 auto_ptr<Y>&& 构造要求 r.release() 能转为 T*,Y 完整,相关 delete 表达式良构、行为良定义且不抛。保存并拥有源释放的指针,后置计数1且源空。可能抛内存或实现定义资源异常;若抛,构造无效果,不能把表达式式描述误读成允许先丢掉源再失败。

p33–34:从 unique_ptr<Y,D>&& 构造,非引用删除器的等效表达式为 shared_ptr(r.release(),r.get_deleter());引用删除器则为 shared_ptr(r.release(),ref(r.get_deleter()))。若异常,构造无效果。这是11本版表达式式描述,不据此编写忽略异常保证的两步实现,也不增加现代版的空源分支。

原创别名安全例(11,静态阅读):

#include <memory>
struct Record { int code; explicit Record(int n) : code(n) {} };
void alias_11() {
std::shared_ptr<Record> whole = std::make_shared<Record>(7);
std::shared_ptr<int> field(whole, &whole->code);
whole.reset();
int copied = *field;
(void)copied;
} // 最后的field销毁时,清理完整Record,不是delete字段地址
whole.get() -> Record 整体 whole ---+
+--> 同一拥有关系 --> 删除 Record
field.get() -> Record::code field ---+

构造 shared_ptr<int>(&whole->code) 是另一回事,会尝试建立独立拥有关系,并不共享原来的完整对象清理责任;不要这样替代别名构造。

20.7.2.2.2 shared_ptr 析构 [util.smartptr.shared.dest]

跳转到“20.7.2.2.2 shared_ptr 析构 [util.smartptr.shared.dest]”

p1:若无拥有关系,或仍有其他 shared_ptr 共享(计数大于1),不执行对象清理副作用。若是最后所有者且有删除器 d,调用 d(p);否则执行 delete p。这里的 p 是拥有的资源指针,不必等于某个别名句柄的 get()。

p2注:该句柄销毁后,仍共享同组的句柄报告的计数减少1。“没有对象清理副作用”不表示计数不变。

20.7.2.2.3 shared_ptr 赋值 [util.smartptr.shared.assign]

跳转到“20.7.2.2.3 shared_ptr 赋值 [util.smartptr.shared.assign]”

p1–3:从同型或异型 const shared_ptr&、以及原文并列的 auto_ptr<Y>&& 赋值,作用式为 shared_ptr(r).swap(*this),返回 *this。原注说明临时构造/销毁引起的中间计数变化不是可观察副作用,实现可不建立临时;原例 p=p 以及已共享所有权的 q=p 可以是无操作。auto_ptr 路径按本版字面保留,不把源版本的表达式悄悄改写。

p4–5:从同型或异型 shared_ptr&& 移动赋值,等效 shared_ptr(std::move(r)).swap(*this),返回 *this。p6–7:从 unique_ptr&& 赋值也用此移动临时加swap形式,返回 *this。

20.7.2.2.4 shared_ptr 修改器 [util.smartptr.shared.mod]

跳转到“20.7.2.2.4 shared_ptr 修改器 [util.smartptr.shared.mod]”

p1:swap(r) 交换两个句柄内容。p2:无参 reset() 等效 shared_ptr().swap(*this)。p3:reset(p) 等效 shared_ptr(p).swap(*this)。p4:带删除器等效 shared_ptr(p,d).swap(*this)。p5:再带allocator等效 shared_ptr(p,d,a).swap(*this)。因此创建新拥有关系可能失败的reset继承对应构造的要求和异常安全,而不先丢掉旧值。

不要把 reset(get()) 用于“重新接管自己”:那会创建独立的清理责任,并与已有拥有关系冲突。

20.7.2.2.5 shared_ptr 观察器 [util.smartptr.shared.obs]

跳转到“20.7.2.2.5 shared_ptr 观察器 [util.smartptr.shared.obs]”

p1:get() 返回存储地址。p2–4:解引用要求非空存储地址,返回 *get()。当 T=void 时是否声明解引用成员未指定;若声明,其返回类型未指定,但声明本身(不一定包括定义)须良构。

p5–6:箭头访问要求 get()!=0,返回 get()。p7–8:use_count() 返回包括自身在内共享同组的 shared_ptr 个数,无拥有关系时为0;不保证高效。弱引用数不包括在内。

p9–10:unique() 返回 use_count()==1,可能比查询计数更快。原注:用于写时复制时,若 get()==0 不要依赖一个特定值;空地址与拥有关系不同。解释:此外,仅看到计数1并不能作为用户对象免同步写入的通用证明。

p11:显式布尔转换只判断 get()!=0。p12:两种 owner_before(参数分别为 shared_ptr<U>、weak_ptr<U>)返回值具体未指定,但须构成严格弱序;双向都为假时,等价当且仅当双方共享所有权或均无拥有关系。不同别名地址可在这套关系中等价。

20.7.2.2.6 shared_ptr 工厂 [util.smartptr.shared.create]

跳转到“20.7.2.2.6 shared_ptr 工厂 [util.smartptr.shared.create]”

来源:11 印刷557,PDF573;p1–7。完整声明按同版印刷552的总览:

template<class T, class... Args>
shared_ptr<T> make_shared(Args&&... args);
template<class T, class A, class... Args>
shared_ptr<T> allocate_shared(const A& a, Args&&... args);

PDF副本字形差异:印刷557函数段的 make_shared 行在像素中显示 Args&...args,而印刷552总览清楚显示 Args&&...args;本段采用同版总览声明,并明确保留该字形差异,不将文本抽取器的输出直接当成接口变更证据。下述两者的作用文字均通过 std::forward<Args>(args)... 构造。

p1:在足够且适合 T 的存储上,::new(pv) T(std::forward<Args>(args)...) 须良构;allocator须符合要求且其复制、析构不抛。p2:取得适合 T 的存储,再以该放置new表达式构造对象;allocate_shared 使用allocator副本取得内存。异常则无效果。

p3–4:返回保存并拥有新对象地址的 shared_ptr,后置非空且计数1。p5:可抛 bad_alloc、A::allocate 的异常或 T 构造的异常。p6:鼓励但不要求至多一次内存分配;“必定单次分配”不是本版保证。p7注:通常申请多于 sizeof(T) 的内存,以存放引用计数等内部记录。标准不固定控制块布局或引用计数的机器表示。

20.7.2.2.7 shared_ptr 比较 [util.smartptr.shared.cmp]

跳转到“20.7.2.2.7 shared_ptr 比较 [util.smartptr.shared.cmp]”

来源:11 印刷557–558,PDF573–574;p1–9。声明全集如下;部分关系函数在本节没有独立展开编号款,仍由总览列出。

template<class T, class U>
bool operator==(const shared_ptr<T>& a, const shared_ptr<U>& b) noexcept;
template<class T, class U>
bool operator!=(const shared_ptr<T>& a, const shared_ptr<U>& b) noexcept;
template<class T, class U>
bool operator<(const shared_ptr<T>& a, const shared_ptr<U>& b) noexcept;
template<class T, class U>
bool operator>(const shared_ptr<T>& a, const shared_ptr<U>& b) noexcept;
template<class T, class U>
bool operator<=(const shared_ptr<T>& a, const shared_ptr<U>& b) noexcept;
template<class T, class U>
bool operator>=(const shared_ptr<T>& a, const shared_ptr<U>& b) noexcept;
template<class T> bool operator==(const shared_ptr<T>& a, nullptr_t) noexcept;
template<class T> bool operator==(nullptr_t, const shared_ptr<T>& a) noexcept;
template<class T> bool operator!=(const shared_ptr<T>& a, nullptr_t) noexcept;
template<class T> bool operator!=(nullptr_t, const shared_ptr<T>& a) noexcept;
template<class T> bool operator<(const shared_ptr<T>& a, nullptr_t) noexcept;
template<class T> bool operator<(nullptr_t, const shared_ptr<T>& a) noexcept;
template<class T> bool operator>(const shared_ptr<T>& a, nullptr_t) noexcept;
template<class T> bool operator>(nullptr_t, const shared_ptr<T>& a) noexcept;
template<class T> bool operator<=(const shared_ptr<T>& a, nullptr_t) noexcept;
template<class T> bool operator<=(nullptr_t, const shared_ptr<T>& a) noexcept;
template<class T> bool operator>=(const shared_ptr<T>& a, nullptr_t) noexcept;
template<class T> bool operator>=(nullptr_t, const shared_ptr<T>& a) noexcept;

p1:相等比较返回 a.get()==b.get()。p2:< 返回 less<V>()(a.get(),b.get()),V 是 T* 和 U* 的复合指针类型(5.9)。p3注:比较使共享指针可作为关联容器键。这不是 owner_before 的按拥有关系排序。

p4–5:与空指针的两侧 == 都为 !a,两侧 != 都为 (bool)a。p6:两侧 < 分别为 less<T*>()(a.get(),nullptr) 与 less<T*>()(nullptr,a.get())。p7:两侧 > 分别化为 nullptr<a 与 a<nullptr。p8:两侧 <= 分别为 !(nullptr<a) 与 !(a<nullptr)。p9:两侧 >= 分别为 !(a<nullptr) 与 !(nullptr<a)。

解释性关系速查:普通 !=、>、<=、>= 应与其相等/小于关系相协调;本文不把这些解释额外编造为本节不存在的p10等规范款。

20.7.2.2.8 shared_ptr 专用算法 [util.smartptr.shared.spec]

跳转到“20.7.2.2.8 shared_ptr 专用算法 [util.smartptr.shared.spec]”
template<class T> void swap(shared_ptr<T>& a, shared_ptr<T>& b) noexcept;

p1:等效 a.swap(b)。

20.7.2.2.9 shared_ptr 指针转换 [util.smartptr.shared.cast]

跳转到“20.7.2.2.9 shared_ptr 指针转换 [util.smartptr.shared.cast]”

来源:11 印刷558–559,PDF574–575;p1–12。

template<class T, class U>
shared_ptr<T> static_pointer_cast(const shared_ptr<U>& r) noexcept;
template<class T, class U>
shared_ptr<T> dynamic_pointer_cast(const shared_ptr<U>& r) noexcept;
template<class T, class U>
shared_ptr<T> const_pointer_cast(const shared_ptr<U>& r) noexcept;

p1–4:静态转换要求 static_cast<T*>(r.get()) 良构。原版返回说明写:若源无拥有关系,返回空 shared_ptr<T>,否则保存转换后的地址并共享源拥有关系。后置同时要求结果 get() 等于转换后指针,计数与源相同。不要将返回说明中的“空”自行等同于 get()==nullptr;这份标准先前已经允许无拥有关系的非空别名指针。原注警告,直接从转换后的原始地址另构造一个 shared_ptr<T> 看似等价,却会形成双重删除风险。

p5–8:动态转换要求 dynamic_cast<T*>(r.get()) 良构且行为良定义。转换结果非零时保存它并共享源拥有关系;否则返回空句柄。结果 get() 等于动态转换结果。原注同样禁止通过独立接管转换后原始指针冒充共享转换。

p9–12:去const转换要求 const_cast<T*>(r.get()) 良构;原版返回说明与静态转换平行,后置为保存转换后指针、计数相同;同样保留共享拥有关系。const_pointer_cast 不授权修改一个原本真正为const的对象,核心语言限制仍在。

原创安全例(11,静态阅读):

#include <memory>
struct Base { virtual ~Base() {} };
struct Derived : Base { int value = 1; };
void checked_cast() {
std::shared_ptr<Base> b = std::make_shared<Derived>();
if (std::shared_ptr<Derived> d = std::dynamic_pointer_cast<Derived>(b)) {
d->value = 2;
}
}

没有从 b.get() 新建第二套所有权;临时 d 离开作用域也不会在 b 仍拥有时提前删除对象。

20.7.2.2.10 get_deleter [util.smartptr.getdeleter]

跳转到“20.7.2.2.10 get_deleter [util.smartptr.getdeleter]”

来源:11 印刷559,PDF575;p1。

template<class D, class T> D* get_deleter(const shared_ptr<T>& p) noexcept;

若 p 拥有的删除器类型为去cv的 D,返回其地址;否则返回0。只要还有一个拥有该删除器的 shared_ptr,返回指针保持有效;之后是否还有效未指定。原注说有实现可能等所有相关 weak_ptr 消失才销毁删除器,不能据这种可能性延长可移植有效期。默认原始指针构造并不保证能查到某个特定内部删除器类型。

20.7.2.2.11 shared_ptr 流输出 [util.smartptr.shared.io]

跳转到“20.7.2.2.11 shared_ptr 流输出 [util.smartptr.shared.io]”
template<class E, class T, class Y>
basic_ostream<E,T>& operator<<(basic_ostream<E,T>& os, shared_ptr<Y> const& p);

p1–2:效果为 os << p.get(),返回 os。输出服从原始指针适用的流插入重载,不等于自动打印所拥有对象的内容。

20.7.2.3 weak_ptr 类模板 [util.smartptr.weak]

跳转到“20.7.2.3 weak_ptr 类模板 [util.smartptr.weak]”

来源:11 印刷560–562,PDF576–578;总则p1–2。

p1:保存对已由 shared_ptr 管理对象的弱引用;访问对象需通过 lock() 得到 shared_ptr。p2:可复制构造、可复制赋值,可作为标准容器元素;T 可不完整。

template<class T> class weak_ptr {
public:
typedef T element_type;
constexpr weak_ptr() noexcept;
template<class Y> weak_ptr(shared_ptr<Y> const& r) noexcept;
weak_ptr(weak_ptr const& r) noexcept;
template<class Y> weak_ptr(weak_ptr<Y> const& r) noexcept;
~weak_ptr();
weak_ptr& operator=(weak_ptr const& r) noexcept;
template<class Y> weak_ptr& operator=(weak_ptr<Y> const& r) noexcept;
template<class Y> weak_ptr& operator=(shared_ptr<Y> const& r) noexcept;
void swap(weak_ptr& r) noexcept;
void reset() noexcept;
long use_count() const noexcept;
bool expired() const noexcept;
shared_ptr<T> lock() const noexcept;
template<class U> bool owner_before(shared_ptr<U> const& b);
template<class U> bool owner_before(weak_ptr<U> const& b);
};

版本边界:这份11概览没有移动构造/移动赋值声明;两种 owner_before 在此PDF副本的概览和成员段均没有结尾 const,已核像素,故声明按该副本保留。不能以现代标准库的接口补齐后声称是2011原文。

20.7.2.3.1 weak_ptr 构造 [util.smartptr.weak.const]

跳转到“20.7.2.3.1 weak_ptr 构造 [util.smartptr.weak.const]”

p1–2:默认构造为空,计数0。p3:异型弱引用复制与从共享指针构造,仅在 Y* 能隐式转为 T* 时参与重载。p4–5:源无拥有关系时目标也无;否则建立对同组的弱引用并复制源存储指针。后置 use_count()==r.use_count(),不会因为新增一个弱句柄而新增强所有者。

20.7.2.3.2 weak_ptr 析构 [util.smartptr.weak.dest]

跳转到“20.7.2.3.2 weak_ptr 析构 [util.smartptr.weak.dest]”

p1:销毁弱句柄,但对其存储指针指向的对象没有效果。它不负责对象的最后强拥有者清理。

20.7.2.3.3 weak_ptr 赋值 [util.smartptr.weak.assign]

跳转到“20.7.2.3.3 weak_ptr 赋值 [util.smartptr.weak.assign]”

p1:三种赋值(同型弱、异型弱、异型共享)都等效 weak_ptr(r).swap(*this)。p2:实现可用其他方式满足相同效果和保证,不一定建立临时对象。声明返回 weak_ptr&;本节未另列返回说明,不为它杜撰编号款。

20.7.2.3.4 weak_ptr 修改器 [util.smartptr.weak.mod]

跳转到“20.7.2.3.4 weak_ptr 修改器 [util.smartptr.weak.mod]”

p1:swap(r) 交换内容。p2:reset() 等效 weak_ptr().swap(*this),清空弱引用。

20.7.2.3.5 weak_ptr 观察器 [util.smartptr.weak.obs]

跳转到“20.7.2.3.5 weak_ptr 观察器 [util.smartptr.weak.obs]”

p1–2:无拥有关系时 use_count() 返回0,否则为共享同组的 shared_ptr 数,可能不是高效操作。p3–4:expired() 返回 use_count()==0,可能比完整计数查询快。

p5:lock() 声明为 noexcept,返回式写为 expired() ? shared_ptr<T>() : shared_ptr<T>(*this)。这里严格保留11出版文本,不把后来对原子执行的明确措辞加到该编号款。该表达式是规范描述,不应自行拆成用户端两步检查再假定期间对象仍存在;本册示例只做单线程静态推演,不运行线程探针。

p6:两种 owner_before 提供严格弱序,双向比较皆假时,双方当且仅当共享同一拥有关系或均无拥有关系。值的具体顺序未指定。

20.7.2.3.6 weak_ptr 专用算法 [util.smartptr.weak.spec]

跳转到“20.7.2.3.6 weak_ptr 专用算法 [util.smartptr.weak.spec]”
template<class T> void swap(weak_ptr<T>& a, weak_ptr<T>& b) noexcept;

本节的效果段无编号:等效 a.swap(b)。

原创弱引用例(11,静态单线程阅读):

#include <memory>
struct Node {
std::shared_ptr<Node> child;
std::weak_ptr<Node> parent;
};
void no_ownership_cycle() {
std::shared_ptr<Node> root = std::make_shared<Node>();
root->child = std::make_shared<Node>();
root->child->parent = root;
std::weak_ptr<Node> observed = root;
root.reset();
std::shared_ptr<Node> after = observed.lock();
// 无其他强所有者,after为空。
}

父拥有子,子只弱引用父,因此没有强拥有环。若双向都是 shared_ptr,计数不会仅因外部root清空就自然归零;智能指针不是任意对象图的循环垃圾回收器。

20.7.2.3.7 owner_less [util.smartptr.ownerless]

跳转到“20.7.2.3.7 owner_less [util.smartptr.ownerless]”

来源:11 印刷562,PDF578;p1–2。支持共享指针与弱指针混合进行拥有关系比较。

template<class T> struct owner_less;
template<class T> struct owner_less<shared_ptr<T>> {
typedef bool result_type;
typedef shared_ptr<T> first_argument_type;
typedef shared_ptr<T> second_argument_type;
bool operator()(shared_ptr<T> const&, shared_ptr<T> const&) const;
bool operator()(shared_ptr<T> const&, weak_ptr<T> const&) const;
bool operator()(weak_ptr<T> const&, shared_ptr<T> const&) const;
};
template<class T> struct owner_less<weak_ptr<T>> {
typedef bool result_type;
typedef weak_ptr<T> first_argument_type;
typedef weak_ptr<T> second_argument_type;
bool operator()(weak_ptr<T> const&, weak_ptr<T> const&) const;
bool operator()(shared_ptr<T> const&, weak_ptr<T> const&) const;
bool operator()(weak_ptr<T> const&, shared_ptr<T> const&) const;
};

p2:operator()(x,y) 返回 x.owner_before(y)。其注重复严格弱序以及等价类为“共享同组或均空”。11没有透明的 owner_less<void> 概览。这份PDF副本的 weak_ptr::owner_before 未写结尾const,与这里const参数的组合存在可见文字上的不协调;这不是constexpr函数的隐式const情形。本文记录副本现象,不将其认定为ISO原始出版物错误,也不凭现代接口默默修订。

20.7.2.4 enable_shared_from_this [util.smartptr.enab]

跳转到“20.7.2.4 enable_shared_from_this [util.smartptr.enab]”

来源:11 印刷562–564,PDF578–580;p1–11。

p1:T 可继承 enable_shared_from_this<T>,通过继承的 shared_from_this 得到指向自身的共享指针。p2重要原例恢复如下(采用其原例结构,静态阅读,未运行):

struct X : public enable_shared_from_this<X> {};
int main() {
shared_ptr<X> p(new X);
shared_ptr<X> q = p->shared_from_this();
assert(p == q);
assert(!(p < q) && !(q < p)); // 原例说明:p和q共享所有权
}

本例共享所有权由 shared_from_this 的合同保证;单独看到任意两个句柄的地址比较相等,不能反推它们必共享同一拥有关系。

template<class T> class enable_shared_from_this {
protected:
constexpr enable_shared_from_this() noexcept;
enable_shared_from_this(enable_shared_from_this const&) noexcept;
enable_shared_from_this& operator=(enable_shared_from_this const&) noexcept;
~enable_shared_from_this();
public:
shared_ptr<T> shared_from_this();
shared_ptr<T const> shared_from_this() const;
};

p3:T 可不完整。p4:默认和复制构造建立此基类对象。p5:赋值返回 *this。p6:析构销毁基类对象。

p7–9:要求该基类在 T 中可访问,当前基类子对象属于某个 T 对象 t,并且已经至少有一个 shared_ptr p 拥有 &t。返回与 p 共享所有权的指针;后置指向当前对象。const重载返回 shared_ptr<T const>。

p10–11原注给出一种可能实现:内部保存 weak_ptr<T>;默认构造令它为空;复制构造不复制另一对象的拥有关系,赋值只返回自身;shared_from_this() 从这个弱引用构造共享指针。首次建立拥有关系的 shared_ptr 构造可检测基类并登记内部弱引用。这是实现示意而非固定数据布局要求,用户不能依赖内部成员名字。

首次shared_ptr接管对象 -> 内部弱引用记住该拥有关系
shared_from_this() -> 从内部弱引用取得同组shared_ptr
不会: -> 用裸this新建第二个独立所有权组

安全边界:2011 p7要求“已经被拥有”。不能把在普通栈对象、尚未接管的构造期对象上调用的行为,改写为本版保证“总会抛 bad_weak_ptr”;本版此处首先是前置条件不满足。也不要把 shared_ptr<T>(this) 当作替代,它会创建另一份清理责任。11没有 weak_from_this。

20.7.2.5 shared_ptr 原子访问 [util.smartptr.shared.atomic]

跳转到“20.7.2.5 shared_ptr 原子访问 [util.smartptr.shared.atomic]”

来源:11 印刷564–565,PDF580–581;p1–37。本节只作静态规范推演,没有创建线程、运行竞争或未定义行为实验。

p1:多个线程对同一个 shared_ptr 的访问,若完全通过本节函数且把该实例作为第一实参所指对象,则不引入数据竞争。p2:memory_order 含义见29.3。这里是对现有 shared_ptr 的自由函数,不是11存在一个 atomic<shared_ptr<T>> 特化的证明。

template<class T> bool atomic_is_lock_free(const shared_ptr<T>* p);
template<class T> shared_ptr<T> atomic_load(const shared_ptr<T>* p);
template<class T>
shared_ptr<T> atomic_load_explicit(const shared_ptr<T>* p, memory_order mo);
template<class T> void atomic_store(shared_ptr<T>* p, shared_ptr<T> r);
template<class T>
void atomic_store_explicit(shared_ptr<T>* p, shared_ptr<T> r, memory_order mo);
template<class T>
shared_ptr<T> atomic_exchange(shared_ptr<T>* p, shared_ptr<T> r);
template<class T>
shared_ptr<T> atomic_exchange_explicit(shared_ptr<T>* p, shared_ptr<T> r,
memory_order mo);
template<class T>
bool atomic_compare_exchange_weak(shared_ptr<T>* p, shared_ptr<T>* v,
shared_ptr<T> w);
template<class T>
bool atomic_compare_exchange_strong(shared_ptr<T>* p, shared_ptr<T>* v,
shared_ptr<T> w);
template<class T>
bool atomic_compare_exchange_weak_explicit(shared_ptr<T>* p, shared_ptr<T>* v,
shared_ptr<T> w,
memory_order success,
memory_order failure);
template<class T>
bool atomic_compare_exchange_strong_explicit(shared_ptr<T>* p, shared_ptr<T>* v,
shared_ptr<T> w,
memory_order success,
memory_order failure);

p3–5:atomic_is_lock_free(p) 要求 p 非空,返回对此句柄的原子访问是否无锁;不抛异常。不允许直接把“原子”等同于“无锁”。

p6–8:atomic_load(p) 要求 p 非空,返回 atomic_load_explicit(p,memory_order_seq_cst);不抛。p9–12:显式load要求 p 非空,mo 不能是 memory_order_release 或 memory_order_acq_rel;返回 *p,不抛。

p13–15:atomic_store(p,r) 要求 p 非空,等效显式store使用 memory_order_seq_cst;不抛。p16–19:显式store要求 p 非空;本版明确排除的 mo 为 memory_order_acquire 和 memory_order_acq_rel;效果 p->swap(r),不抛。本册不把别版新增的禁止值静默填入这两个原版列表。安全教学例只使用默认顺序,不借遗漏试验边界。

p20–22:atomic_exchange(p,r) 要求 p 非空,返回显式exchange使用顺序一致顺序的结果;不抛。p23–26:显式exchange要求 p 非空,效果 p->swap(r),返回原 *p,不抛。

p27–29:非显式weak比较交换要求 p 非空,调用显式weak版本,成功、失败顺序均为 memory_order_seq_cst;不抛。p30:非显式strong版本委托给显式strong,两个顺序同样为顺序一致。其有效参数要求也通过委托目标保留,不能因这一款没有重复文字就把空 p 当成合法。

p31–32:两种显式CAS要求 p 非空;失败顺序不能为 memory_order_release 或 memory_order_acq_rel,也不能强于成功顺序。v 是用于比较及失败写回的预期值指针,程序当然须提供能够合法访问的目标;本版编号Requires专门列的是 p 和顺序限制。

p33–35:若 *p 与 *v 等价,就把 w 赋给 *p,以成功顺序同步并返回真;否则把实际 *p 写回 *v,按失败顺序同步并返回假。不抛异常。p36:等价要求“存储指针值相同并共享所有权”,不是仅 get() 相同。p37:weak版本允许伪失败,相关一般机制见29.6。因此不能把weak一次返回假必定解释成内容不同。

静态状态图(无线程运行):

CAS输入: target = A,expected = A,desired = B
强CAS成功:target = B,expected仍为A,返回true
CAS输入: target = C,expected = A,desired = B
比较不匹配:target仍为C,expected改为C,返回false
“相同”同时检查地址与拥有关系;weak还允许伪失败

原创安全例(11,仅顺序调用以展示签名):

#include <memory>
void atomic_api_shape() {
std::shared_ptr<int> slot = std::make_shared<int>(1);
std::shared_ptr<int> snapshot = std::atomic_load(&slot);
std::shared_ptr<int> expected = snapshot;
std::shared_ptr<int> desired = std::make_shared<int>(2);
bool changed = std::atomic_compare_exchange_strong(&slot, &expected, desired);
(void)changed;
}

此例没有其他写入者,预期值来自同一个句柄的load,静态上比较匹配。它不测试实现是否无锁,也不证明经句柄访问的 int 在多线程中可无同步修改。若真有并发访问同一 slot,不能混用普通 slot = ... 与这些原子访问函数。

20.7.2.6 智能指针 hash 支持 [util.smartptr.hash]

跳转到“20.7.2.6 智能指针 hash 支持 [util.smartptr.hash]”

来源:11 印刷566,PDF582;p1–2。

template<class T, class D> struct hash<unique_ptr<T,D>>;
template<class T> struct hash<shared_ptr<T>>;

p1:hash<unique_ptr<T,D>> 满足20.8.12的hash模板要求。设 UP=unique_ptr<T,D>,则 hash<UP>()(p) 与 hash<typename UP::pointer>()(p.get()) 相同;相应指针hash特化须良构。

p2:hash<shared_ptr<T>> 也满足hash要求;hash<shared_ptr<T>>()(p) 与 hash<T*>()(p.get()) 相同。它按存储地址哈希,不是按拥有关系控制块哈希;11本节没有 hash<weak_ptr<T>>。

第四部分 跨版边界与复习

跳转到“第四部分 跨版边界与复习”
概念建立动作结束动作不自动完成的事
allocator原始存储allocatedeallocate不自动构造、析构一般元素
放置构造对象生存期construct、放置new、未初始化算法destroy、显式析构不自动归还外层存储
独占所有权接管构造、移动reset、析构、转移get()不转移,release()不销毁
共享所有权首次接管、共享复制、别名共享最后强所有者离开弱引用不延长强拥有期,不自动解除循环
主题C++03本册C++11本册
分配器适配层直接allocator接口;容器可假定同型实例全相等allocator_traits统一访问并提供回退;传播行为结合17章及容器规定
构造接口默认allocator从 const T& 复制构造construct(U*,Args&&...)完美转发
实际地址默认allocator文字写 &x明确绕开重载取址,并提供 addressof
未初始化算法三个;fill_n返回void四个,新增 copy_n;fill_n返回尾迭代器
临时缓冲无显式noexcept和非正请求分支noexcept且 n<=0返回零对
独占工具auto_ptr复制即转移,不能当容器普通可复制元素unique_ptr禁止复制、允许移动;支持删除器和数组特化
共享工具本章没有标准 shared_ptrshared_ptr、weak_ptr、所有权比较、工厂与原子自由函数
对齐/可达性无本册11新增工具align、指针安全登记及trait工具
  1. allocate(n) 得到存储,不表示已存在 n 个构造完成的 T。
  2. 构造失败不能析构该未完成对象;构造数组前缀需要按对应算法和异常合同清理。
  3. 临时缓冲的实际容量必须检查;allocator释放计数必须匹配。
  4. max_size() 不是当前可用内存承诺;11 traits原版回退不是现代除以元素大小的版本。
  5. 删除器的拷贝、移动、赋值、调用各有自己的要求,不能只检查其函数名存在。
  6. 单对象 delete 与数组 delete[] 必须匹配;能进行派生到基类指针转换不等于能安全删除。
  7. unique_ptr::get() 不转交所有权;release() 让旧管理者放手,不负责后续清理。
  8. shared_ptr 空拥有关系、空存储地址、计数为零、布尔值为假不可在所有场景互换。
  9. 从已有句柄的裸地址独立接管,会产生第二份删除责任;共享转换与别名构造须用专用接口。
  10. owner_before 按拥有关系,普通比较和hash按存储地址。
  11. shared_from_this 在2011条文中先要求已被共享指针拥有,不能把违例统一宣称为确定异常。
  12. 共享计数线程安全不等于所指对象线程安全,也不等于同一个句柄普通并发写安全。
  13. 原子CAS比较不仅比地址;weak允许伪失败;失败时预期参数被写回实际值。
  14. 11没有 make_unique、数组 make_shared、weak_from_this、to_address、owner_less<void>、atomic<shared_ptr<T>> 特化等后续接口。

本册证据与静态审查边界

跳转到“本册证据与静态审查边界”

规范来源仅为本册开头两份用户PDF;03本册全部页可读,11本册全部页可读。逐节标题、编号款、表31–34和45–46、脚注214/216/229均已纳入,另保留未编号的规范说明。声明中的规范占位 see below 与原标准算法作用式不是独立可编译程序;原例、原创安全例均明确标记。

对损字采用同版总览、成员段和像素共同检查。此PDF副本中的可见字面差异独立注明,包括11 allocator_traits::max_size 的const形参差别、make_shared 个别行的引用符字形差别、weak_ptr::owner_before 的非const声明;不假造标准缺陷编号,不使用后来的网页或实现补原版。示例全部为静态论证,没有编译运行C++、开启线程或执行未定义行为测试。