简体   繁体   English

C ++中静态局部变量的范围和生存期

[英]The scope and lifetime of static local variable in c++

#include<iostream>
using namespace std;

int &fun()
{
    static int x = 10;
    return x;
}
int main()
{
    fun() = 30;
    cout << fun();
    return 0;
}

when the above program is run,the output is 30.The integer variable x was returned,as a reference to the main() function and it is assigned the value of 30.But isn't the scope of x limited to the fun() function?;If so,why are we able to change the value of it in main function?? 当上述程序运行时,输出为30。返回整数变量x作为对main()函数的引用,并为其分配了值30。但是x的范围不限于fun( )函数?;如果是,为什么我们可以在主函数中更改它的值?

Scope is limited means any attempt to access x directly outside the scope is forbidden. 范围是有限的,这意味着禁止在范围外直接访问x任何尝试。

Within a scope, unqualified name lookup can be used to associate the name with its declaration. 在范围内,可以使用非限定名称查找将名称与其声明相关联。

But you can always return a pointer or reference to this variable if variable is alive and you change it through that reference or pointer which points to the same variable. 但是,如果变量是活动的,则始终可以返回指向该变量的指针或引用,并且可以通过指向同一变量的引用或指针对其进行更改。 The name of this reference may be anonymous (temporary) or may be bound to some named reference. 该引用的名称可以是匿名的(临时的),也可以绑定到某些命名的引用。

About lifetime, it starts when the function containing static variable is called first time and ends when the program end. 关于生存期,它在包含静态变量的函数被首次调用时开始,并在程序结束时结束。

Indeed the scope of x is limited to fun() . 事实上范围x 限制在fun()

But because that function returns a reference to x , the caller (ie main ) is able to modify x through that reference. 但是由于该函数返回对x引用 ,因此调用者(即main )能够通过该引用修改x That's what's happening here: x is set to 10 the first time the function is entered, but is changed to 30 by the assignment fun() = 30 . 这就是这里发生的情况: 一次输入该函数时, x设置为10 ,但通过赋值fun() = 30更改为fun() = 30

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

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