在 C++ 中,用自身初始化全局变量是否具有未定义的行为? [英] In C++, does initializing a global variable with itself have undefined behaviour?

查看:39
本文介绍了在 C++ 中,用自身初始化全局变量是否具有未定义的行为?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

int i = i;

int main() { 
 int a = a;
 return 0;
} 

int a = a 肯定有未定义的行为(UB),更多细节在正在阅读未初始化的值总是未定义的行为?或者有例外吗?.

int a = a surely has undefined behaviour (UB), and more details on it is in Is reading an uninitialized value always an undefined behaviour? Or are there exceptions to it?.

但是 int i = i 呢?在 C++ 中,我们可以为全局变量分配非常量值.i 在遇到声明之前被声明和零初始化(因为它具有文件范围).在这种情况下,我们稍后在定义中将 0 分配给它.可以说这没有 UB 吗?

But what about int i = i? In C++ we are allowed to assign nonconstant values to globals. i is declared and zero initialized (since it has file scope) before the declaration is encountered. In which case we are assigning 0 to it later in the definition. Is it safe to say this does not have UB?

推荐答案

令人惊讶的是,这并不是未定义的行为.

Surprisingly, this is not undefined behavior.

静态初始化[basic.start.static]

Static initialization [basic.start.static]

如果是变量或临时对象,则执行常量初始化静态或线程存储持续时间是常量初始化的.如果不执行常量初始化,一个带有静态的变量存储持续时间或线程存储持续时间为零初始化.零初始化和常量初始化统称为静态初始化;所有其他初始化都是动态的初始化.所有静态初始化强烈发生在任何动态初始化.

Constant initialization is performed if a variable or temporary object with static or thread storage duration is constant-initialized. If constant initialization is not performed, a variable with static storage duration or thread storage duration is zero-initialized. Together, zero-initialization and constant initialization are called static initialization; all other initialization is dynamic initialization. All static initialization strongly happens before any dynamic initialization.

重要部分加粗.静态初始化"包括全局变量初始化、静态存储持续时间"包括全局变量,上面的子句在这里适用:

Important parts bold-faced. "Static initialization" includes global variable initialization, "static storage duration" includes global variables, and the above clause is applicable here:

int i = i;

这不是常量初始化.因此,零初始化是根据上述条款完成的(对于基本整数类型零初始化意味着,毫不奇怪,它被设置为 0).上述条款还规定在动态初始化之前必须进行零初始化.

This is not constant-initialization. Therefore, zero-initialization is done according to the above clause (for basic integer types zero-initialization means, unsurprising, that it's set to 0). The above clause also specifies that zero initialization must take place before dynamic initialization.

那么,这里发生了什么:

So, what happens here:

  1. i 被初始化为 0.
  2. i 然后从自身动态初始化,所以它仍然是 0.
  1. i is initialized to 0.
  2. i is then dynamically initialized, from itself, so it still remains 0.

这篇关于在 C++ 中,用自身初始化全局变量是否具有未定义的行为?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆