从概念上来说,构造函数的执行能够分红两个阶段,初始化阶段和计算阶段,初始化阶段先于计算阶段。ios
在执行构造函数时,若是没有给定初始值,那系统就会自动进行初始化。函数
#include <stdlib.h> #include <iostream> #include <string>
class myclass { public: int num_i; float num_f; double num_d; char chr; std::string str; }; int main() { myclass test; std::cout << test.chr << std::endl; std::cout << test.str << std::endl; std::cout << test.num_i << std::endl; std::cout << test.num_f << std::endl; std::cout << test.num_d << std::endl; system("pause"); }
初始化列表是在初始化阶段对成员变量进行复制,所以使用初始化列表比构造函数更加快速。性能
能够经过比较使用初始化列表和不适用初始化列表的构造函数的执行时间来进行测试。测试
不使用初始化列表:spa
#include <stdlib.h> #include <iostream> #include <string> #include <time.h> #include <Windows.h>
class myclass { public: myclass(std::string *str) { mystr = new std::string[1000]; mystr = str; } private: std::string *mystr; }; int main() { time_t start,end; std::string *str = new std::string[1000]; for (int i = 0; i < 1000; i++) str[i] = "hello"; start = clock(); myclass n_class(str); end = clock(); std::cout << "函数执行时间:" <<(end - start)*1000/CLOCKS_PER_SEC;//精确到毫秒
std::cout << "\n"; system("pause"); }
使用初始化列表:code
#include <stdlib.h> #include <iostream> #include <string> #include <time.h> #include <Windows.h>
class myclass { public: myclass(std::string *str) :mystr(new std::string[1000]) { mystr = str; } private: std::string *mystr; }; int main() { time_t start,end; std::string *str = new std::string[1000]; for (int i = 0; i < 1000; i++) str[i] = "hello"; start = clock(); myclass n_class(str); end = clock(); std::cout << "函数执行时间:" <<(end - start)*1000/CLOCKS_PER_SEC;//精确到毫秒
std::cout << "\n"; system("pause"); }
由执行的结果能够看出,在使用初始化列表函数执行的更加快速。blog