C++ Assign a const value at run-time?

2020-07-06 07:53发布

问题:

I have a constant value that never changes during run-time, but is impossible to know until run-time.

Is there a way to declare a constant (either as a member of a class or not) without defining it and also assign a computed value once (and only once) it is determined; or am I going to have to resort to a non-const declaration and use coding S & Ps (ALL_CAPS variables names, static declaration if in a class, etc.) to try and keep it from changing?

CLARIFICATION:

Though these are good answers, the real-world situation I have is more complicated:

The program has a main loop that continually runs between processing and rendering; the user can set required options and once they are set they will never change until the program is restart. An "Initialize" function is set up for anything that can be determined before the main loop, but values that are dependent on user interaction must be performed in the middle of the loop during the processing phase. (At the moment, persistent data storage techniques come to mind...)

回答1:

Something like this?

const int x = calcConstant();

If it's a class member, then use the constructor initialisation list, as in Yuushi's answer.



回答2:

You can define it in a struct or class and utilize an initialisation list:

#include <iostream>

struct has_const_member
{
    const int x;

    has_const_member(int x_)
      : x(x_)
    { }

};

int main()
{
    int foo = 0;
    std::cin >> foo;
    has_const_member h(foo);
    std::cout << h.x << "\n";
    return 0;
}


回答3:

As a static or function-local variable:

const int x = calcConstant();

As a class member:

struct ConstContainer {
    ConstContainer(int x) : x(x) {}
    const int x;
};


回答4:

Yes, you can make a private static singleton field with an initialization method and a gettor method. Here's an example of how to do it:

// In foo.h
class Foo
{
public:
    // Caller must ensure that initializeGlobalValue
    // was already called.
    static int getGlobalValue() { 
        if (!initialized) {
            ... handle the error ...
        }
        return global_value; 
    }

    static void initializeGlobalValue(...)

private:
    static bool initialized;
    static int  global_value;
};

// In foo.cpp
bool Foo::initialized = false;
int Foo::global_value;

void Foo::initializeGlobalValue(...) {
    if (initialized) {
        ...handle the error...
    }
    global_value = ...;
    initialized = true;
}