Effective C++

1.尽量以const,enum,inline替换#define

1
2
3
4
5
6
7
//.h
class Foo{
private:
static const int NUM = 5;//class专属常量声明
}
//.cpp
const int Foo::NUM;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
char grerting[] = "hello";
char* p = grerting; //non-const pointer non-const data
const char* p = grerting;// non-const pointer const data
char* const p = grerting;// const pointer non-const data
const char* const p = grerting;// const pointer const data

std::vector<int> vec;
const std::vector<int>::iterator iterator = vec.begin();
*iterator = 0;// ok
++iterator;// error iterator is const

std::vector<int>::const_iterator iterator = vec.begin();
*iterator = 0;// error ,*iterator is const
++iterator;// ok
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
class Text{
public:
const char& operator[](std::size_t position) const {
//do something
return text[position];
}

//const_cast转换符移除变量的const
//static_cast<new_type>(expression):expression->new_type
char& operator[](std::size_t position){
//do something
return const_cast<char&>(
static_cast<const Text&>(*this)[position]);
}

private:
std::string text;
};

class Text{
public:
Text(std::string str):text(str){};//效率高,直接初始化值
Text(std::string str){
text = str; //效率低,先调用default设初值,再赋值
};
private:
std::string text;
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class FileSystem{
//...
};

FileSystem& tfs(){
static FileSystem tfs;
return tfs;
}

class Directory{

};

Directory::Directory(params){
std::size_t disks = tfs().numDisks();//避免无序的初始化
}
Directory& tempDir(){
static Directory td;
return td;
}

2.可禁止使用copy构造函数或copy assignment操作符,使其私有并只作声明

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
class HomeForSale{
public:
...
private:
HomeForSale(const HomeForSale &);
HomeForSale& operator=(const HomeForSale&);
}
//or
class Uncopyable{
protected:
//允许derived对象构造和析构
Uncopyable(){};
~Uncopyable(){};
private:
//阻止copying
Uncopyable(const Uncopyable &);
Uncopyable& operator=(const Uncopyable&);
}

class HomeForSale : private Uncopyable{
...
}


HomeForSale home;
HomeForSale new_home(home);//error
HomeForSale new_home_assign;
new_home_assign = home;//error

3.带多态性质的基类应该声明一个virtual析构函数,如果class带有任何virtual函数,都应拥有一个virtual析构函数

否则调用delete时,删除由base class指针指向的derived class,derived class的析构函数不会被执行,仅执行base class的析构函数

1
2
3
4
5
6
7
8
9
10
class TimeKeeper{
public:
TimeKeeper();
virtual ~TimeKeeper();
...
}
TimeKeeper *ptk = getTimeKeeper();
...
delete ptk;

4.令operator=返回一个reference to this指针

1
2
3
4
5
6
7
8
class TimeKeeper{
public:
TimeKeeper& operator=(const TimeKeeper& rhs){
this.name = rhs.name;
...
return *this;
}
}

5.


Effective C++
https://jiaopaner.github.io/2021/01/12/effective c++/
作者
JiaoPan
发布于
2021年1月12日
许可协议