c++ - 类中的 C++ 静态函数,返回引用
问题描述
经过一番研究后,我不明白输出(下面的源代码):
42
42
45
我对第二个很好,但为什么我得到这个输出?它来自于在更大的项目中避免使用全局常量和变量。有人可以向我解释一下吗?
#include <iostream>
class Const
{
public:
Const() = delete;
static auto foo(int val = 42) -> int&;
};
auto Const::foo(int val) -> int&
{
static int sval = val;
return sval;
}
int main()
{
std::cout << Const::foo() << std::endl;
Const::foo(24);
std::cout << Const::foo() << std::endl;
Const::foo() = 45;
std::cout << Const::foo() << std::endl;
return 0;
}
解决方案
在您的代码中:
#include <iostream>
class Const // what a strange name for something that is not const.
{
public:
Const() = delete;
static auto foo(int val = 42) -> int&;
};
auto Const::foo(int val) -> int& // if you don't return a const reference,
// it may be modified by the caller
{
static int sval = val; // val is not const, and only initialized
// once.
return sval; // you return a reference to a mutable value.
}
int main()
{
std::cout << Const::foo() << std::endl;
Const::foo(24); // this changes nothing, the static variable sval
// has already been initialized.
std::cout << Const::foo() << std::endl;
Const::foo() = 45; // the reference returned by foo() is
// not const. SO that works.
std::cout << Const::foo() << std::endl;
return 0;
}
为了解决这个问题,Const::foo() 应该返回一个 const int&。
忘记使用静态函数变量。进入函数时,代码必须每次检查其静态变量是否已初始化。这通常涉及使用硬件围栏或其他一些线程安全机制。这些将不必要地减慢执行速度,尤其是在从多个线程访问这些 const 值时。
推荐阅读
- c++ - 为什么当我反转 LinkList 时出现分段错误(核心转储)?
- gnuradio - 使用 RTL-SDR 加密狗的 Z-Wave 的 GNURadio Companion Blocks
- ruby-on-rails - Rails ActiveRecord mysql2 适配器,默认使用 PreparedStatement
- python-3.x - 具有异步函数的 Python 多处理
- python - 如何使用python将数据放入csv文件?
- android - 如何在滑动回收站视图项目时创建执行操作。就像在 gmail 应用程序中滑动删除选项一样。但不应删除回收站视图项
- java - 在调用 getter 方法时获取 NullPointerException
- ms-word - officejs:无法将超链接文本的下划线属性设置为 false
- c - 拆分 char[] 并将值存储在不同的数组中 C
- arrays - 如何找到所有大小为 k 的子数组的第 n 个最小值/最大值(滑动窗口问题)