需要注意三点:
1. 手工初始化内置型的非成员对象
2. 使用初始化成员列表对付对象的所有成员
3. 对 "初始化顺序不确实" 的问题要注意自己的设计.
这里重点介绍下第三种的情况:
下面的 tfs 会在外部文件 b.cpp 中使用, 但是当前这种写法不能够保证 tfs 在 b.cpp 中使用时已经被初始化了, 这样就会造成问题.
- //a.h
- class FileSystem
- {
- public:
- int numDisk() const;
- };
- extern FileSystem fs; // 只是声明
- //a.cpp
- FileSystem fs; // 这里是定义
- ///b.cpp
- class Directory
- {
- public:
- Directory(string params)
- {
- int disks = fs.numDisks(); // 因为 a.cpp 和 b.cpp 在编译时并不能保证先后顺序, 有可能出现 tfs 还没有被初始化, 就被使用的情况
- }
- };
把 tfs 声明为一个函数, 返回对象的引用, 这样 b.cpp 中去调用时, 就能够保证 fs 一定是初始化了的. 不过这里我有个疑问, 作者为什么要用静态变量的引用呢? 不可以是局部变量吗? 或者不使用引用吗?
- //a.h
- class FileSystem // 库中定义的类
- {
- public:
- int numDisks() const;
- };
- //a.cpp
- FileSystem &tfs()// 这样写, 表示 tfs() 是一个全局函数, 而非成员函数.
- {
- static FileSystem fs; //C++ 保证函数中的 local static 对象会在 "该函数被调用期间"" 首次遇上该对象的定义式 " 时被初始化.
- return fs;
- }
- //b.cpp
- class Directory
- {
- public:
- Directory(string params)
- {
- int disks = tfs().numDisks();
- }
- };
来源: http://www.bubuko.com/infodetail-3345351.html