条款04: 确定对象被使用前已被初始化
1. 对象使用之前进行初始化
void Test00() { int x = 0; const char* text = "A C-style string"; double d; std::cin >> d; }
1. 使用初始化列表进行初始化
2. baseClass的初始化早于derivedClass
3. class的成员变量总是以声明的顺序进行初始化,而不是在成员初值列中的顺序
class PhoneNumber {}; class ABEntry { public: ABEntry() : theName(), theAddress(), thePhones(), numTimesConsulted(0) {} ABEntry(const std::string& name, const std::string& address, const std::list<PhoneNumber>& phones) : theName(name), theAddress(address), thePhones(phones),numTimesConsulted(0) {} private: std::string theName; std::string theAddress; std::list<PhoneNumber> thePhones; int numTimesConsulted; };
1. 初始化次序的重要性,tfs在tempDir之前先被初始化,否则tempDir的构造函数会用到尚未初始化的tfs
2. 定义并初始化一个local static对象,以免除"跨编译单元之初始化次序"
class FileSystem { public: size_t numDisks() { return 1u; } }; FileSystem& tfs() { static FileSystem fs; return fs; } class Directory { public: Directory() { std::size_t disks = tfs().numDisks(); } }; Directory& tempDir() { static Directory td; return td; }
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步