研究了一下之后,我不明白输出(下面的源代码):
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;
}
答案 0 :(得分: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值时。