主要的区别就是默认构造函数对内置类型的初始化上。如果没有T中没有定义构造函数,则对于“T t”,并不会对 t 中内置类型设置初始值,是一个随机值。但对于“T t = T()”,对 t 中内置类型会设置初始值,如 int 类型会设置为0。而对于自定义类型,不管哪种方式,都会调用构造函数初始化。
#include <iostream>using namespace std;class Inside {public:int getMem() { return _mem; }private:int _mem;};class Outside {public:int getMem() { return _mem; }void printInside() {cout << _in.getMem() << endl;}private:int _mem;Inside _in;};int main() {Outside o1;Outside o2 = Outside();cout << o1.getMem() << " " << o2.getMem() << endl;o1.printInside();o2.printInside();return 0;}
上面代码的输出为:
4196848 000
可见只有o1的内置类型成员没有被初始化为0。但此时如果对Outside类添加了一个空函数体的构造函数,可以得到结果如下:
4196864 1044243872032767
o2 的内置类型成员及其成员变量 _in 的内置类型都没有被初始化,因为这个时候Outside的构造函数为空,也就不会调用 _in 的构造函数初始化了,所以都是随机数。
不过比较奇怪的是 o1 的 _in 的内置类型还是被初始化为 0 了,这个需要自己再深入了解下了。