两者之间的重要区别
class B {
public:
B(){}
int i;
int j;
};
and
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规定
To value-initialize an object of type T means:
— if T is a (possibly
cv-qualified) class type (Clause 9) with a user-provided constructor
(12.1), then the default constructor for T is called (and the
initialization is ill-formed if T has no accessible default
constructor);
— 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.
例如:
#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;
}
可能的结果:
0,0
0,0
145084416,0
0,0
145084432,0
0,0
145084416,0
//...
http://ideone.com/k8mBrd