简体   繁体   English

C ++ 14非聚合上的统一初始化

[英]C++14 Uniform Initialization on a Non-Aggregate

I'm using Visual C++ 2013. When the class is an aggregate it is zero-initialized. 我正在使用Visual C ++ 2013.当类是聚合时,它是零初始化的。 When it's a non-aggregate it seems to be default-initialized and left indeterminate. 当它是非聚合时,它似乎是默认初始化并且不确定。 Why is that? 这是为什么?

#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();
}

If your compiler is doing this, it's broken. 如果您的编译器正在执行此操作,则它已损坏。

[dcl.init.list]/p3 (all quotes are from N4140): [dcl.init.list] / p3(所有报价均来自N4140):

List-initialization of an object or reference of type T is defined as follows: 列表初始化对象或类型T引用定义如下:

  • If T is an aggregate, aggregate initialization is performed (8.5.1). 如果T是聚合,则执行聚合初始化(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. 否则,如果初始化程序列表没有元素且T是具有默认构造函数的类类型,则对象将进行值初始化。
  • [...] [...]

[dcl.init]/p8: [dcl.init] / P8:

To value-initialize an object of type T means: 对值类型T的对象进行值初始化意味着:

  • 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; 如果T是一个(可能是cv限定的)类类型(第9条),没有默认构造函数(12.1)或者是用户提供或删除的默认构造函数,那么该对象是默认初始化的;
  • 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; 如果T是一个(可能是cv限定的)类类型而没有用户提供或删除的默认构造函数,那么该对象是零初始化的,并且检查默认初始化的语义约束,如果T有一个非平凡的默认构造函数,该对象是默认初始化的;
  • if T is an array type, then each element is value-initialized; 如果T是数组类型,那么每个元素都是值初始化的;
  • otherwise, the object is zero-initialized. 否则,该对象被零初始化。

Test_2 is not an aggregate, so t2 should have been value-initialized. Test_2不是聚合,因此t2应该已经过值初始化。 In turn, since Test_2 's default constructor is not user-provided, t2 is supposed to be first zero-initialized (causing t2.i to be initialized to 0), and then the default constructor is run. 反过来,由于Test_2的默认构造函数不是用户提供的,因此t2应该首先进行零初始化(使t2.i初始化为0),然后运行默认构造函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM