Can I initialize a static const member at run-time in C++?

前端 未结 11 1090
小蘑菇
小蘑菇 2020-12-09 16:22

Is it possible to initialize a static const member of my class during run-time? This variable is a constant throughout my program but I want to send it as a command-line arg

11条回答
  •  甜味超标
    2020-12-09 16:54

    You cannot rely on data produced after your main has started for initialization of static variables, because static initialization in the translation unit of main happens before main gets control, and static initialization in other translation units may happen before or after static initialization of main translation unit in unspecified order.

    However, you can initialize a hidden non-const variable, and provide a const reference to it, like this:

    struct A {
    public: 
        // Expose T as a const reference to int
        static const int& T;
    };
    
    //in main.cpp
    
    // Make a hidden variable for the actual value
    static int actualT;
    // Initialize A::T to reference the hidden variable
    const int& A::T(actualT);
    
    int main(int argc,char** argv) {
        // Set the hidden variable
        actualT = atoi(argv[1]);
        // Now the publicly visible variable A::T has the correct value
        cout << A::T << endl;
    }
    

    Demo.

提交回复
热议问题