[英]C++ static function in class, return reference
After researching a bit I don't understand the output (source code below):经过一番研究后,我不明白 output(下面的源代码):
42 42
42 42
45 45
I'm fine with the second, but why I get this output?我对第二个很好,但为什么我得到这个 output? It's coming from fooling around with avoiding global constants and variables in a bigger project.它来自于在更大的项目中避免使用全局常量和变量。 Could someone please explain it to me?有人可以向我解释一下吗?
#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;
}
In your code:在你的代码中:
#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;
}
To fix, Const::foo() should return a const int&.要解决这个问题,Const::foo() 应该返回一个 const int&。
Forget about using static function variables.忘记使用 static function 变量。 When entering the function, the code must check each time if its static variables have been initialized.当输入function时,代码每次都要检查其static变量是否已经初始化。 This usually involves using a hardware fence or some other thread-safe mechanism.这通常涉及使用硬件栅栏或其他一些线程安全机制。 These will unnecessarily slow down execution, especially when accessing these const values from multiple threads.这些会不必要地减慢执行速度,尤其是在从多个线程访问这些 const 值时。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.