更改对函数中静态变量的引用的值
Changing the value of a reference to a static variable in a function
请考虑以下C++代码片段:
#include <iostream>
using namespace std;
int &fun()
{
static int a = 10;
return a;
}
int main(int argc, char const *argv[])
{
int &y = fun();
y += 30;
cout << fun();
return 0;
}
输出:40
上面给出的代码片段的输出如何证明是合理的?
fun
不是函数指针,它是一个返回int&
的空函数。具体来说,它返回对名为 a
的static int
的引用。
因此,您的程序所做的是:
int &y = fun(); // this is the first call to fun, so we initialize a.
// it now has a value of 10, and we return a reference to it
// so y is a reference to the static variable local to fun()
y += 30; // y == 40
// since y is a reference to "fun::a", a is now 40 too
cout << fun(); // a is static, so it will only get initialized once.
// that first line is effectively a NOOP, so fun() just
// returns a reference to it. which has a value of 40.
您没有使用函数指针,而只是将调用fun
的结果存储在引用中。
a
是静态变量,您正在初始化对该变量的引用。在这种情况下,引用只是a
的另一个名称,所以这就是为什么修改引用的值y
,你也会修改值a
,这是静态的,这意味着它的值在调用之间被保留。
相关文章:
- C++Boost Asio Pool线程,带有lambda函数和传递引用变量
- 多个"常量引用"变量可以共享同一个内存吗?
- 如果非动态变量被指针引用,何时超出范围?
- 在 c++ 中将变量作为结构构造函数中的引用传递
- 在 gtest 中初始化堆栈上的引用变量的隔离错误
- 为什么C++可以使用未初始化的成员变量(引用或指针 *NOT 值复制*)来初始化其父类的成员变量
- 地址运算符是否返回变量引用的对象的地址
- 未在另一个函数中设置变量引用的问题
- 英特尔样式内联程序集和 AT&T 样式中的变量引用,C++
- 将成员变量引用为类成员
- 从静态变量引用非静态变量会使非静态变量先于静态变量进行析构函数
- 何时解析 C++11 lambda 表达式中的变量引用
- 堆栈/堆变量的变量/引用名称或类型存储在内存中的位置
- C++强制对变量引用进行编译优化,使之成为直接的
- Boost变量引用和相等比较
- 使复制的成员引用变量引用副本的成员,而不是原始成员的成员
- 为什么要在Java中生成变量引用数组
- 捕获和调试对移动lambda内部局部变量引用的无效使用
- 在变量初始化后更改变量引用
- 从'C'程序中提取变量定义和变量引用