您的位置:首页 > 编程语言 > C语言/C++

《Effective C++》与《More Effective C++》笔记总结

2016-02-18 20:11 501 查看
1. 对于常量,最好使用const对象或enums替代#defines

2. 对于类似宏的函数,最好使用Template inline替代#defines

3. 如果const出现在*左边,表示data是常量;如果const出现在*右边,表示pointer是常量

char greeting = "Hello"
const char* p = greeting; // const data
char* const p = greeting; // const pointer


4. 对于在const函数中需要改变某些变量的值:使用mutable关键字修饰变量

5. 当const和non-const函数中有重复代码:在non-const函数中调用const函数

const char& operator[](std::size_t position) const
{
return text[position];
}
char& operator[](std::size_t position)
{
return
const_cast<char&>( //去除op[]返回值的const
static_cast<const TextBlock*>(*this) //为*this加上const
[position];
);
}


6. class creates following specific member functions implicitly:

a. default constructor; b. copy constructor; c. copy assignment operator; d. destructor

7. 将拷贝构造函数和赋值运算符重载声明为private,可以避免被意外调用。

8. 什么时候要将析构函数声明为virtual:

a. 对于具有多态(polymophic)的base class; b. 如果class中有任一virtual函数

9. 如果class中有纯虚函数,那么这是一个abstract class,它不能被实例化

10. 在析构函数中如果有异常发生,要进行捕捉

try{ close(); }
catch(...){
// log
// std::abort();
}


11. 在构造函数和析构函数中不调用virtual function。因为此时不会下到derived层。

12. operator=的结构:

T& operator=(const T& rhs)
{
if (this == &rhs) return *this;
...
return *this;
}


13. 写一个copying函数的时候,需要确保

a. copy all local member; b. 调用base classes内部的copying函数

14. copy构造函数与copy assignment操作符代码重复时:抽一个新的函数,通常命名为init,声明为private,让两个copy调用

15. 智能指针auto_ptr,执行复制动作会使被复制物指向null;shared_ptr的复制不会。

16. 复制智能指针对象:a. 复制底部资源(deep copying)b. 转移底部资源的所有权(auto_ptr)

17. 对于base class作为函数参数,应使用by reference-to-const(const T&)的方式传递参数,以避免slicing问题

因为passed by value会调用拷贝构造函数构造一个新的对象,那么属于derived class的内容就会消失

18. 类型转换:

a. const_cast: 去除常量的const标志

b. dynamic_cast: 有继承关系的向下类型转换,消耗大

c. static_cast: 强制类型转换,除了去除const之外

d. reinterpret_cast: 低级转型
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: