for (int i = 0; i < NUM; i++) {
Data d(dataFile);
d.process();
}
使用 init:
[cpp]
// 设 init 是 re-init 式的
Data d;
for (int i = 0; i < NUM; i++) {
d.init(dataFile);
d.process();
}
init 赚不了什么便宜,而使用构造函数的版本可籍由 拖延构造对象手法 获利,见 [EFFECT CPP] Item 26
pimpl^
见 [EFFECT CPP] Item 14, 25, 29, 31
pimpl (Pointer to Implementation) 实质是实现 (Implementation) 和封装 (Wrapper) 分离,Bjarne 习惯把 Implementation 叫做 表示 (Representation)
注意:
开销:
空间开销变小:只有 pimpl 指针
时间开销变大:多了解引操作
施行拷贝 (assgin, copy ctor) 的方式:
Shallow Copy 浅拷贝:仅拷贝 pimpl 指针,例如标准 SP:auto_ptr, share_ptr
深拷贝使 wrapper 具有值语义 (Value Semantics),又拷贝语义
Deep Copy 深拷贝:拷贝 pimpl 所指物
浅拷贝使 wrapper 具有引用语义 (Reference Semantics),如果想使浅拷贝具有值语义,可用 RC + COW (Copy on Write) 写时复制手法
Reference Counting^
见 [EFFECT CPP] Item 13, 14; [MEFFECT CPP] Item 17, 29
Reference Counting (RC) 引用计数
一般不用从零写 RC 类,只要类中包含 RC 的组成部分即可,如利用 share_ptr 成员
Sample:
class Person: RC + COW 简单示例
class String: 改自 [CPP LANG] 11.12 A String Class
技术:pimpl, RC, COW, Proxy class。Proxy class 用以区分 operator[] 的读写语义:R-value Usage vs. L-value Usage,见 [MEFFECT CPP] Item 17, 30
功能:值语义的 string 类示例,没有模板化之 CharType、CharTraits 和 Allocator
Bjarne: That done, we can throw away our exercises and use the standard library string. (Ch.20)
Smart Pointer^
见 [CPP LANG] 11.10 Dereferencing, 14.4.2 auto_ptr; [EFFECT CPP] Item 13, 14, 15, 17, 18; [MEFFECT CPP] Item 28; [BOOST TUTORIAL] 3.1~3.7
Smart Pointer (SP) 智能指针是一种 Delegation of Raw Pointer 机制,技术上等于:RAII + pimpl + Ownership Semantics 所有权语义
常用 SP 助记(来自 stdlib/Boost/TR1):
_ptr vs. _array 后缀
ptr 型托管单体对象 (new),array 型托管对象数组 (new[])
array 型有 [] 操作(不检查下标范围),没有 *, -> 操作
array 型可用 vector 或 ptr 型 + vector 代替
scoped 型
所有权:Monopolize 独占,又 Noncopyable
注意:不能用于值语义之 STL 容器的元素
auto 型
所有权:Transfer 转移,又 Distructive Copy 破坏性拷贝
注意:不能用于值语义之 STL 容器的元素
shared 型
所有权:Share 共享,又 RCSP (Reference-Counting Smart Pointer) 引用计数型智能指针
特点:支持 deleter, Cross-DLL, Raw Pointer 访问
注意:Cycles of References 环状引用问题
见
weak_ptr
所有权:Observe 观察
特点:伪 SP,不独立使用,而是配合 shared_ptr 使用以解决环状引用问题
见
intrusive_ptr
特点:size 和 raw pointer 相同,利用被托管对象已有的 RC 机制(侵入式)
CComPtr, CComQIPtr
ATL 中托管 COM 接口的 SP,均派生自 CComPtrBase,自动执行 COM 引用计数 AddRef 和 Release
CComQIPtr 使用 COM 接口 IID
Sample:
class AutoPtr, AutoArr: 可指定上文所述 deleter 的 auto 型 SP
摘自 Breaker 的日志