《Effective C++》第三版-0 导读(Introduction)
《Effective C++》第三版-1. 让自己习惯C++(Accustoming Yourself to C++)
条款01:视C++为一个语言联邦(View C++ as a federation of languages)
C++有4个主要的次语言(sublanguage):
- C。包含区块(blocks)、语句(statements)、预处理器(preprocessor)、内置数据类型(built-in data)、数组(arrays)、指针(pointers)等;没有模板(templates)、异常(exceptions)、继承(inheritance)。
- Object-Oriented C++。这是C with classes部分,包含classes(包括构造函数和析构函数)、封装(encapsulation)、继承(inheritance)、多态(polymorphism)、virtual函数等。
- Template C++。这是C++泛型编程(generic programming)部分。
- STL。涉及容器(containers)、迭代器(iterators)、算法(algorithms)、函数对象(function objects)。
《Effective C++》第三版-2. 构造析构赋值运算(Constructors,Destructors,and Assignment Operators)
《Effective C++》第三版-3. 资源管理(Resource Management)
前几章的笔记多有不足,这一章会持续改进
条款13:以对象管理资源(Use objects to manage resources)
1 关键想法
考虑以下易出错的例子:
class Investment { ... }; //投资类型继承体系中的root类
//工厂函数,指向Investment继承体系内的动态分配对象,参数省略
Investment* createInvestment {};
void f()
{
Investment* pInv = createInvestment(); //调用工厂函数
... //若这里return则无法执行delete
delete pInv; //释放pInv所指对象
}《Effective C++》第三版-4. 设计与声明(Design and Declarations)
《Effective C++》第三版-5. 实现(Implementations)
条款26:尽可能延后变量定义式的出现时间(Postpone variable definitions as long as possible)
应延后变量的定义,知道不得不使用该变量的前一刻为止,甚至直到能够给他初值实参为止
当程序的控制流达到变量的定义式时,会有构造成本;当离开变量的作用域时,会有析构成本
std::string encryptPassword(const std::string& password)
{
...
std::string encrypted(password); //通过copy构造函数定义并初始化
encrypt(encrypted);
return encrypted;
}