Make函数将全局变量视为const

C++: Make function treat global variable as const

本文关键字:const 全局变量 函数 Make      更新时间:2023-10-16

我有以下设置:

Foo.cpp

class Bar {
public:
    inline Bar() : x(0), y(0), z(0) {}
    inline Bar(int X, int Y, int Z) : x(X), y(Y), z(Z) {}
    const int x, y, z;
};
static Bar globalBar;
static void foo() {
    int x = globalBar.x; // the compiler should assume globalBar is const here!
    ...
}
void almightySetup() {
    globalBar = Bar(meaningOfLife(), complexCalc(), magic());
    startThread(foo); // foo() will NEVER be called before this point!
    // globalBar will NEVER be changed after this point!
}

可以看到,编译器在指定的点假定globalBarconst是安全的,因为在设置之后,globalBar在该点之后将永远不会改变。此外,foo()在设置之前不会被调用。

但是我怎么才能做到这一点呢?我试过使用const_cast<>,但不断得到类型错误信息。我一定是做错了什么。这可能吗?

我应该补充一点,我不能随意更改foo的函数签名

这是一个理论上的例子。我还没有测试过,但是我很想听听c++专家的意见。这能行吗?

static Bar globalBar;
static void foo() {
    static const Bar myGlobalBar = globalBar;
    int x = myGlobalBar .x; // the compiler should assume globalBar is const here!
    ...
}