简体   繁体   English

为什么全局变量在编译时不知道?

[英]Why global variables are not known at compile-time?

In C++, I know that if a I declared a variable inside a function, this variable is actually considered as auto local variable (destroyed once a function does return ).在 C++ 中,我知道如果我在 function 中声明了一个变量,则该变量实际上被视为auto局部变量(一旦 ZC1C425268E68385D1AB5074C17A94F14 确实return就被销毁)。 So it stands to reason that, a local variable cannot appears in a constant expression like an initializer for a constexpr variable, because simply it known at runtime, it needs the function in which it declared to be executed and that's happening only at runtime.因此,有理由认为,局部变量不能像constexpr变量的初始化程序那样出现在常量表达式中,因为它在运行时就知道,它需要在其中声明要执行的 function 并且仅在运行时发生。

int x { 10 };
constexpr int y { x }; //error: x should be const

int main()
{
    //..
}

My question is, what would happen if this variable is global?我的问题是,如果这个变量是全局的会发生什么? So no runtime functions need to be executed in order to know the value of x , because it does not belong to any functions?所以不需要执行运行时函数来知道x的值,因为它不属于任何函数? My question, in other words, when does exactly the compiler knows the value of this variable x我的问题,换句话说,编译器什么时候知道这个变量x的值

I already know that, if the variable x is const, then x will be a constant expression but why is that?我已经知道,如果变量x是 const,那么x将是一个常量表达式,但这是为什么呢?

In your particular example, the compiler can possibly know.在您的特定示例中,编译器可能知道。 It just doesn't have to.它只是不必。

But what if you have但是如果你有

int x { 10 };
someclass trix{};
constexpr int y { x }; //error: x should be const

Now the constructor for trix just could modify x , and the compiler wouldn't know.现在trix的构造函数可以修改x ,编译器不知道。 Especially if trix.cpp is compiled after the main file.特别是如果 trix.cpp 在主文件之后编译。

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

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