简体   繁体   English

C ++命名空间范围变量的初始化

[英]C++ initialization of namespace scope variable

Consider following program: (see live demo here. ) 考虑以下程序:(请参见此处的现场演示

#include <iostream>
inline double fun()
{
    return 3.0;
}
extern double m;
double d2=m;
int main()
{
    std::cout<<d2;
}
double m=fun();

I was expecting to get output of program as 3.0 but it gives me output 0. Why? 我原本希望将程序的输出输出为3.0,但输出为0。为什么?

It looks like variable d2 is initialized statically? 看起来变量d2是静态初始化的吗?

Shouldn't it be initialized dynamically? 它不应该动态初始化吗?

I've tested it on g++ 4.8.1, 4.9.2 & MSVS 2010 & get 0 as an output. 我已经在g ++ 4.8.1、4.9.2和MSVS 2010上进行了测试,并获得0作为输出。

Variables within a C++ file are initialized top-to-bottom. C++文件中的变量从上到下初始化。 So m is initialized after d . 所以md之后初始化。

There are some other subtleties. 还有其他一些细微之处。

When the compiler can work it out, it sometimes emits data definitions for variables - setting a value to a known constant. 当编译器可以解决该问题时,有时会发出变量的数据定义-将值设置为已知常量。 These occur before the program is loaded. 这些发生在程序加载之前。

Then the order of initialization is the code segments - like constructors. 然后初始化的顺序是代码段-类似于构造函数。 These segments occur top to bottom in the compilation unit. 这些段在编译单元中从上到下出现。

In your case d=m I think copies the value from the slot for m. 在您的情况下, d=m我认为是从插槽复制d=m的值。 Which is set to 0.0 设置为0.0

Then m=fun() is called, copying the slot with the correct value. 然后,调用m=fun() ,并使用正确的值复制插槽。

Yes, both d2 and m have static storage duration, because they are declared, undecorated, at namespace scope. 是的,因为d2m都具有静态存储持续时间,因为它们是在名称空间范围内未经装饰地声明的。

That means they are zero-initialised as a first step before any other initialisation happens. 这意味着在进行任何其他初始化之前,将它们初始化为零 Then, d2 is set to m . 然后,将d2设置为m It is not until after that, that m becomes 3.0 . 直到那之后 m变为3.0

Consider the following, which is essentially the same thing: 考虑以下内容,这基本上是相同的:

int main()
{
   int x = 0, y = 0;
   y = x;
   x = 3;
}

Clearly, here, it is nonsense to expect y to be equal to 3 , but that's what you're doing. 显然,在这里,期望y等于3是胡说八道,但这就是您正在做的事情。

If you expected the initialisation to happen like for function- static variables, where initialisation happens on first use ( sort of ), you were mistaken. 如果您希望初始化会像函数static变量那样发生,而初始化是在首次使用时发生的( 某种程度上 ),那您就错了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM