gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:34:20 26 4
gpt4 key购买 nike

我使用的是 Visual C++ 2013。当类是聚合时,它是零初始化的。当它是非聚合时,它似乎是默认初始化的并且不确定。这是为什么?

#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),然后运行默认构造函数。

关于C++14 非聚合的统一初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28391796/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com