静态变量与自身的初始化 [英] Initialisation of static variable with itself

查看:170
本文介绍了静态变量与自身的初始化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑以下代码示例:

#include <iostream>

static int bar = bar;

int main()
{
    int foo = foo;
    std::cout << "foo = " << foo << std::endl;
    std::cout << "bar = " << bar << std::endl;
}

我得到以下编译器警告:

I get following compiler warning:

main.cpp: In function 'int main()':
main.cpp:7:15: warning: 'foo' is used uninitialized in this function [-Wuninitialized]
     int foo = foo;
               ^

输出:

foo = 0
bar = 0



期望这个警告作为foo使用单元化。而不是0,'foo'可以是任何东西。
自定义未定义。

I expected this warning as foo is used unitialised. Instead of 0, 'foo' can be anything. Self-assignment is undefined.

但是为什么'bar'的自我赋值不会被警告呢?这是'bar'定义或未定义的行为的分配和为什么?

But why is the the self-assignment of 'bar' not warned? Is this assignment of 'bar' defined or undefined behaviour and why?

我知道,元素数据类型的静态变量初始化为'0',但在这种情况下,在其初始化期间使用变量bar。我想知道,如果这是定义的行为和'0'是预期的输出。 (这将解释,没有编译器警告发生)。

I know, static variables of elementar data types are initialised with '0' but in this case, the variable 'bar' is used during its initialisation. I'm wondering, if this is defined behaviour and the '0' is the expected output. (Which would explain, that no compiler warning occurs).

链接to live example

推荐答案

我相信标准的一部分与您的问题相关(§3.6.2/ 2):

I believe that part of the standard is relevant to your question (§3.6.2/2):


具有静态存储持续时间(3.7.1)或线程存储持续时间(3.7.2)的变量应进行零初始化[...]

Variables with static storage duration (3.7.1) or thread storage duration (3.7.2) shall be zero-initialized (8.5) before any other initialization takes place.[...]

所以在这种情况下,甚至在编译之前看看你的定义 bar ,它已经零初始化了它。

So in this case, even before the compiler looks at your definition of bar, it has already zero-initialized it.

在标准中,静态变量初始化应该有两个阶段(强调我的)。

As it is specified a bit further in the standard, there shall be two phases for static variables initialization (emphasis mine).


静态初始化;所有其他初始化
动态初始化必须在执行任何动态初始化之前执行静态初始化

Together, zero-initialization and constant initialization are called static initialization; all other initialization is dynamic initialization. Static initialization shall be performed before any dynamic initialization takes place.

这篇关于静态变量与自身的初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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