1、C++里的C语言部分,不保证会初始化变量;C++里的C++部分,会初始化变量。初始化会导致运行期成本。所以C语言中的数组不保证会初始化,而C++中的vector数组保证会初始化。
2、初始化时间
1)内置类型 - 手动初始化,赋值时即可初始化,初始化和赋值成本相同
2)其他类型(包括对象) - 构造函数
如何初始化
1、第一个版本:构造函数
需要注意赋值和初始化的区别
注:
theName、theAddress、thePhones,初始化的时间:调用他们各自的构造函数时,先于进入ABEntry构造函数,所以代码中的只是对他们进行赋值,而不是初始化
2、第二个版本:初始化列表
ABEntry::ABEntry(const std::string& name,const std::string& address,const std::list<PhoneNumber>& phones):theName(name),theAddress(address),thePhones(phones),numTimesConsulted(0) {}ABEntry::ABEntry(const std::string& name,const std::string& address,const std::list<PhoneNumber>& phones):theName(),theAddress(),thePhones(),numTimesConsulted(0) {}
注:
1)第一个版本:theName、theAddress、thePhones调用其默认构造函数初始化,结果又被重新赋值,初始化显得多余。所以可以采用初始化列表的方式,直接调用拷贝构造
2)如果成员变量是const和引用,那么一定用初始化列表的方式
3)初始化成员次序
不同编译单元的non-local static对象
一个编译单元的non-local static对象,使用到了另一个编译单元没有被初始化的non-local statci对象,会报错。因为C++并不保证不同编译单元的non-local static对象的初始化顺序
1、extern关键字
2、
//fileSystem.h#include<iostream>using namespace std;class FileSystem {public:void provide();};FileSystem tfs;
//customer.h#include <iostream>using namespace std;class Customer {public:Customer();};
//提供给外部使用的文件系统fileSystem.cpp#include "fileSystem.h"void FileSystem::provide() {cout << "FileSystem provides customer" << endl;}
//客户端customer.cpp#include "customer.h"Customer::Customer() {//fileSystem提供给外部使用的接口//当c初始化时,无法保证tfs已经被初始化extern FileSystem tfs;tfs.provide();}int main() {Customer c;return 0;}
报错:无法保证两个编译单元的non-local static对象的初始化顺序,当c初始化时,无法保证tfs已经被初始化。
用local static对象替代non-local static对象
1、前提:C++保证,当首次遇到local static对象时,对象会被初始化。
2、单例模式的常见实现方式:用函数调用的方式替代直接使用non-local static对象,优点:保证函数返回的引用一定是被初始化的,而且可以根据需要,如果不使用函数,就绝对不会造成初始化的成本开销
C++ 单例模式
#include<iostream>using namespace std;class FileSystem {public:void provide();};class Customer {public:Customer();};FileSystem& tfs();Customer& customer();void FileSystem::provide() {cout << "FileSystem provides customer" << endl;}Customer::Customer() {tfs().provide();}//用函数调用替代直接使用non-local static对象FileSystem& tfs() {//定义并初始化local static对象static FileSystem fs;//返回一个引用return fs;}//用函数调用替代直接使用non-local static对象Customer& customer() {//定义并初始化local static对象static Customer c;//返回一个引用return c;}int main() {Customer c;return 0;}
总结
1、尽量使用初始化列表的方式(有的时候必须,而且高效)
1)成员变量是const和引用类型,必须使用初始化列表
2)成员变量是内置类型,初始化和赋值成本相同
3)成员变量是其他类型(比如对象),先调用成员变量的构造函数,再进入到类的构造函数(可能会进行赋值),为了节省开销,使用初始化列表
2、C - 不保证初始化变量(比如数组),C++ - 保证初始化变量(比如vector)
3、non-local static对象无法保证在不同编译单元下,初始化顺序,很容易发生使用了其他没有被初始化的non-local static对象
解决办法:用local static对象来替代non-local static对象,即用函数调用的方式来替代直接访问non-locla static对象
