这本书有九个章节,每一个章节都对特定C++使用方面进行了讲述,并提供了一些建议(条款),本篇笔记也将以书本顺序编写并配以目录,以方便读者快速查阅。

让自己习惯C++

explicit

  • 禁止类对象之间的隐式转换,以及禁止隐式调用拷贝构造函数。

eg:

先看看不使用explicit的时候,以下代码会把10调用对象之间的隐式转换,这样exp1的值就变成了{10, 1}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>
using namespace std;

class B {
public:
B(int x = 0, bool b = true);
};

B::B(int x, bool b) {
cout << x << ": " << sizeof(x) << endl;
cout << b << ": " << sizeof(b) << endl;
}

int main() {
B exp1 = 10;
return 0;
}

如果加上了explicit关键字,编译时就会报错
“pre.cpp: In function ‘int main()’:
pre.cpp:15:14: error: conversion from ‘int’ to non-scalar type ‘B’ requested
B exp1 = 10;”

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>
using namespace std;

class B {
public:
explicit B(int x = 0, bool b = true);
};

B::B(int x, bool b) {
cout << x << ": " << sizeof(x) << endl;
cout << b << ": " << sizeof(b) << endl;
}

int main() {
B exp1 = 10;
return 0;
}

Prefer consts,enums,and inlines to #define

  • 在程序编译阶段前的预处理阶段,由define定义的符号会被做文本替换,也就是说实际上当程序运行时,那个被替换的符号已经没有被记录了(符号表不记录)。这样当你的程序出现错误时,编译器报出的错误你将难以判别了。
1
#define A 1.22

改成

1
const double A 1.22

const

  • const 出现在 * 左边,被指向的物是常量; const 出现在 * 右边, 指针自身是常量。
    也是就说一下两种写法其实含义是相同的。
1
2
void f1(const int* a);
void f1(int const * a);
  • 当你想给一个类中的某个变量予以不变的常量,并且这个类的实例都可以访问它
1
2
3
4
5
class A {
private:
static const int a = 5;
int arrs[a];
}

inline

  • inline 会把标识符处的函数名展开成函数体,以免去函数调用的消耗,并且能够正常的进行类型检查与调试功能。
    相比于define函数宏所可能带来意外的运行,更推荐使用inline
1
#define CALL_WITH_MAX(a, b) f((a) > (b) ? (a) : (b))
1
2
3
4
template<typename T>
inline void callWithMax(const T& a, const T& b) {
f(a > b ? a : b);
}