之间的重要区别
class B {
public:
B(){}
int i;
int j;
};
和
class B {
public:
B() = default;
int i;
int j;
};
是定义的默认构造函数B() = default;
被认为不是用户定义的。这意味着在值初始化的情况下
B* pb = new B(); // use of () triggers value-initialization
将发生根本不使用构造函数的特殊类型的初始化,对于内置类型,这将导致零初始化。在B(){}
这种情况下不会发生。C++ 标准 n3337 § 8.5/7 说
对 T 类型的对象进行值初始化意味着:
— 如果 T 是具有用户提供的构造函数(12.1)的(可能是 cv 限定的)类类型(第 9 条
),则调用 T 的默认构造函数(如果 T 没有可访问的默认构造函数,则初始化是非良构的);
— if T is a (possibly cv-qualified) non-union class type
without a user-provided constructor, then the object is
zero-initialized and, if T’s implicitly-declared default constructor
is non-trivial, that constructor is called.
— if T is an array type,
then each element is value-initialized; — otherwise, the object is
zero-initialized.
For example:
#include <iostream>
class A {
public:
A(){}
int i;
int j;
};
class B {
public:
B() = default;
int i;
int j;
};
int main()
{
for( int i = 0; i < 100; ++i) {
A* pa = new A();
B* pb = new B();
std::cout << pa->i << "," << pa->j << std::endl;
std::cout << pb->i << "," << pb->j << std::endl;
delete pa;
delete pb;
}
return 0;
}
possible result:
0,0
0,0
145084416,0
0,0
145084432,0
0,0
145084416,0
//...
http://ideone.com/k8mBrd