C++14 非聚合的统一初始化
C++14 Uniform Initialization on a Non-Aggregate
我正在使用 Visual C++ 2013。当 class 是一个聚合时,它是零初始化的。当它是非聚合时,它似乎是默认初始化的并且不确定。这是为什么?
#include <iostream>
using namespace std;
class Test_1
{
public:
int i;
void f(){};
};
class Test_2
{
public:
int i;
virtual void f(){};
};
int main()
{
Test_1 t1{};
Test_2 t2{};
cout<<t1.i<<endl; //0
cout<<t2.i<<endl; //-858993460
getchar();
}
如果你的编译器这样做,它就坏了。
[dcl.init.list]/p3(所有引用均来自 N4140):
List-initialization of an object or reference of type T
is defined
as follows:
- If
T
is an aggregate, aggregate initialization is performed (8.5.1).
- Otherwise, if the initializer list has no elements and
T
is a class type with a default constructor, the object is
value-initialized.
- [...]
[dcl.init]/p8:
To value-initialize an object of type T
means:
- if
T
is a (possibly cv-qualified) class type (Clause 9) with either no default constructor (12.1) or a default constructor that is
user-provided or deleted, then the object is default-initialized;
- if
T
is a (possibly cv-qualified) class type without a user-provided or deleted default constructor, then the object is
zero-initialized and the semantic constraints for
default-initialization are checked, and if T has a non-trivial default
constructor, the object is default-initialized;
- if T is an array type, then each element is value-initialized;
- otherwise, the object is zero-initialized.
Test_2
不是一个集合,所以 t2
应该被值初始化。反过来,由于 Test_2
的默认构造函数不是用户提供的,因此 t2
应该首先被零初始化(导致 t2.i
被初始化为 0),然后是默认的构造函数是 运行。
我正在使用 Visual C++ 2013。当 class 是一个聚合时,它是零初始化的。当它是非聚合时,它似乎是默认初始化的并且不确定。这是为什么?
#include <iostream>
using namespace std;
class Test_1
{
public:
int i;
void f(){};
};
class Test_2
{
public:
int i;
virtual void f(){};
};
int main()
{
Test_1 t1{};
Test_2 t2{};
cout<<t1.i<<endl; //0
cout<<t2.i<<endl; //-858993460
getchar();
}
如果你的编译器这样做,它就坏了。
[dcl.init.list]/p3(所有引用均来自 N4140):
List-initialization of an object or reference of type
T
is defined as follows:
- If
T
is an aggregate, aggregate initialization is performed (8.5.1).- Otherwise, if the initializer list has no elements and
T
is a class type with a default constructor, the object is value-initialized.- [...]
[dcl.init]/p8:
To value-initialize an object of type
T
means:
- if
T
is a (possibly cv-qualified) class type (Clause 9) with either no default constructor (12.1) or a default constructor that is user-provided or deleted, then the object is default-initialized;- if
T
is a (possibly cv-qualified) class type without a user-provided or deleted default constructor, then the object is zero-initialized and the semantic constraints for default-initialization are checked, and if T has a non-trivial default constructor, the object is default-initialized;- if T is an array type, then each element is value-initialized;
- otherwise, the object is zero-initialized.
Test_2
不是一个集合,所以 t2
应该被值初始化。反过来,由于 Test_2
的默认构造函数不是用户提供的,因此 t2
应该首先被零初始化(导致 t2.i
被初始化为 0),然后是默认的构造函数是 运行。