gpt4 book ai didi

c++ - 字符串和字符串数组的零初始化(C++)

转载 作者:搜寻专家 更新时间:2023-10-31 02:02:26 26 4
gpt4 key购买 nike

根据 https://en.cppreference.com/w/cpp/language/zero_initialization

enter image description here

在文档提供的例子中:

std::string s; // is first zero-initialized to indeterminate value
// then default-initialized to ""

如果语法用于static T object;,为什么string s; 会出现零初始化?

为什么零初始化发生在默认初始化之前,为什么两者都允许发生?

零初始化的效果是:

  • If T is a scalar type, the object's initial value is the integral constant zero explicitly converted to T.
  • If T is an non-union class type, all base classes and non-static data members are zero-initialized, and all padding is initialized to zero bits. The constructors, if any, are ignored.
  • If T is a union type, the first non-static named data member is zero-initialized and all padding is initialized to zero bits.
  • If T is array type, each element is zero-initialized
  • If T is reference type, nothing is done.

如果我初始化 string array[2] = {"Test1"}; 会怎样?我知道该数组将包含“Test1”和空字符串“”。

但是根据上面的文档,

If T is array type, each element is zero-initialized

数据类型是字符串,是对象/引用类型?

If T is reference type, nothing is done.

什么都没做?我想也许会调用一个构造函数。肯定是空字符串吧?

最佳答案

(除非另有说明,否则假定此答案中的所有声明都在命名空间范围内。)

Why does zero initialization occur to string s; if the syntax is for static T object;?
Why does zero initialization happen before default initialization and why are both allowed to happen?

具有静态存储持续时间的变量首先在编译时被零初始化,然后可选择地在运行时动态初始化。 static T object; 声明一个静态存储持续时间的对象。对于像

这样的简单声明
int x;

不执行动态初始化。对于更复杂的声明,例如

std::string s;

对字符串进行零初始化可能会导致类不变量损坏的无效字符串。因此,动态初始化调用默认构造函数来保证对象有效。

What if I initialize string array[2] = {"Test1"};? I know that the array will contain "Test1" and empty string "".

首先,在编译时,两个对象被零初始化,导致可能的无效状态。然后,在运行时调用构造函数(const char* 第一个对象的构造函数和第二个对象的默认构造函数),并构造有效的对象。

The data type is string which is an object / reference type?

std::string 是对象类型而不是引用类型。

[For a reference type] Nothing is done? I thought maybe a constructor would have been called. Surely an empty string is something?

引用类型不被视为实际的“对象”,因此没有必要指定其零初始化语义。

关于c++ - 字符串和字符串数组的零初始化(C++),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57283036/

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