gpt4 book ai didi

c++ - 值初始化c++

转载 作者:行者123 更新时间:2023-11-27 23:41:58 25 4
gpt4 key购买 nike

阅读 cppreference on value initialization,我得到了这个:

  1. if T is a class type with no default constructor or with auser-provided or deleted default constructor, the object isdefault-initialized;

例子:

struct T3
{
int mem1;
std::string mem2;
T3() { } // user-provided default constructor
};

阅读有关默认的文章 initialization

if T is a non-POD (until C++11) class type, the constructors areconsidered and subjected to overload resolution against the emptyargument list. The constructor selected (which is one of the defaultconstructors) is called to provide the initial value for the newobject;

if T is an array type, every element of the array isdefault-initialized;

otherwise, nothing is done: the objects with automatic storageduration (and their subobjects) are initialized to indeterminatevalues.

这适用于示例,T 是类类型,这意味着重载决议应该选择初始化值的候选者(用户提供的默认构造函数),但它是空的,所以 mem1应该保留不确定的值(这是真的)但同样应该是 mem2,但这是“默认初始化”为“”,这是为什么呢?它递归地工作吗? T 的每个类类型成员都服从第一条规则?

我现在很困惑。


2)if T is a class type with a default constructor that is neitheruser-provided nor deleted (that is, it may be a class with animplicitly-defined or defaulted default constructor), the object iszero-initialized and then it is default-initialized if it has anon-trivial default constructor;

例子:

struct T1
{
int mem1;
std::string mem2;
}; // implicit default constructor

mem1 被零初始化为 0,但是“非平凡的”默认构造函数是什么意思? mem2 也默认初始化为“”,但我仍然不确定,“非平凡的默认构造函数”是什么意思?默认构造函数应该由编译器生成,但是它如何决定什么是非平凡的,什么不是非平凡的——如果非平凡的默认构造函数意味着它必须初始化对象——与上面相同的问题,这是否意味着每个对象都使用默认构造函数初始化?

最佳答案

same should be mem2, but that is "default initialized" to "", why is that? Does it work recursively? Every member of T that is class type is subjected to first rule?

您的猜测是正确的。当你默认初始化类时,你默认初始化它的每个成员,因为你的构造函数中没有指定初始化。由于 std::string 有一个用户提供的默认构造函数,它被调用并将字符串对象初始化为空。

however what does "non-trivial" default contructor means?

平凡的构造函数是什么都不做的构造函数。对于 T 类型,如果

,它的构造函数是微不足道的
  • 构造函数不是用户提供的(即隐式定义或默认)
  • T 没有虚成员函数
  • T 没有虚基类
  • T 没有带大括号或等号初始值设定项的非静态成员。
  • T 的每个直接基类都有一个平凡的默认构造函数
  • 类类型的每个非静态成员都有一个简单的默认构造函数

因此在 T1 的情况下,您没有平凡的构造函数,因为 std::string 的默认构造函数是非平凡的。

关于c++ - 值初始化c++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54029509/

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