简体   繁体   中英

C++: Make function treat global variable as const

I have the following setup:

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!
}

As you can see, it is safe for the compiler to assume that globalBar is const at the indicated point, because globalBar , after setup, will never be changed after that point. Furthermore, foo() will not be called before it is setup.

But how can I accomplish this? I've tried using const_cast<> but keep getting type error messages. I must be doing something wrong. Is it even possible?

I should add that I am not at liberty to change the function signature of foo .

This is a theoretical example. I haven't tested it but would love opinions from C++ experts. Would this work?

static Bar globalBar;

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM