首页 > 解决方案 > 类中的 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;
}

标签: c++referencestaticstd

解决方案


在您的代码中:

#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 值时。


推荐阅读