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

Zero initialization of string and string array (C++)

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

在文档提供的示例中:

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?

在您链接到的页面中,它定义了一个非局部变量。

非局部变量分两个阶段初始化。

  1. 静态初始化。
  2. 动态初始化(如果适用)。

静态初始化阶段,使用常量初始化零初始化初始化变量

Dyanmic initialization is used, if it applies, such as for objects that have the appropriate constructor or for objects that are initialized using an expression that can be evaluated at [=41] 如果适用,则使用动态初始化 =]时间。

您可以在 https://en.cppreference.com 上阅读有关该主题的更多信息。

Nothing is done? I thought maybe a constructor would have been called. Surely an empty string is something?

引用不能被零初始化。它只能使用将作为引用的对象进行初始化。

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

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;

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

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?

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