[Effective C++] 学习笔记之编译器OR预处理器?

1. 被声明为explicit的构造函数

声明为explicit的构造函数禁止编译器执行非预期(往往不被期望的)的类型转换,可以阻止隐式类型转换,但允许显式类型转换(强制类型转换)。
鼓励使用这一声明,除非你有一个好的理由允许构造函数进行隐式类型转换。

2. 拷贝构造

Pass-by-value也是通过调用拷贝构造函数

class Widget{
public:
	Widget(){}//缺省构造函数
	Widget(const Widget& rhs);//拷贝构造函数
	Widget& operator=(const Widget& rhs);//拷贝操作符
	hasAccQuality(Widget w);
}
...
Widget w1;//调用缺省构造函数
Widget w2(w1);//调用拷贝构造函数
w1 = w2;//调用拷贝操作符
Widget w3 = w2;//调用拷贝构造函数
if(w3.hasAccQuality(w2))//调用拷贝构造函数
...

3. 命名习惯

  1. lhs:left hand side
  2. rhs:right hand side
  3. pt:pointer to T,指向T类型对象的指针
  4. rt:reference to T,T类型对象的引用

4. 多线程问题

C++对多线程问题需要额外注意,线程安全是一个不容忽视的问题。

5. C++联邦

C++是一个联邦,同时支持过程形式,面向对象形式,函数形式,泛型形式、元编程形式;C、Object-Oriented C++、Template C++、STL是需要好好学习的四个方面。

6. 用编译器代替预处理器

Prefer const, enum and inline to #define!!!
#define 的记号不会进入记号表里面,但出现错误时,难以追踪。

#define CircleRadius 1.68543   
const double CircleRadius = 1.68543; //更好

指向常量的常量指针

const std::string sAuthorName("Jack-lct"); //std::string 比char*-base字符串更好
const char* const pAuthorName = "Jack-lct"; 

class 专属常量,头文件声明+实现文件定义,无法使用 #define

class A{
...
static const int ANumber ;//头文件中声明
...
}
...
const int A::ANumber = 10;//实现文件中定义

无法使用 in class初值设定,使用enum hack技术

class GamePlayer{
...
private:
	enum{NumberTurn =5};
	int scores[NumberTurn];
}

使用 template inline 函数

#define CALL_WITH_MAX(a,b) f((a) > (b) ? (a) : (b)) //不好,会有潜在问题

template <typename T>
inline void callWithMax(const T& a, const T& b){
	f(a>b?a:b);
} //好

Reference

[1] Scott Meyers. 电子工业出版社. Effective C++中文版[M]. 2006.

发布了8 篇原创文章 · 获赞 7 · 访问量 435

猜你喜欢

转载自blog.csdn.net/sinat_38161291/article/details/104764033