Search code examples
theorysolid-principles

Does there exist the concept of set-once variables?


I am wondering if anyone has developed the concept of a set-once variable. That is, a variable that perhaps has some default value, but can be set only once during program execution. Note this differs from any kind of constant, as constants are set before program execution.


Solution

  • There's no prepackaged solution for this, but since we have once_flag now, we could write an overkill solution that guarantees that you can only call operator= once:

    template <typename T>
    class SetOnce
    {
    public:
        SetOnce(T const& v)
        : val(v)
        { }
    
        SetOnce& operator=(T const& v) {
            std::call_once(flag, [=]{
                val = v;
            });
            return *this;
        }
    
        T get() const { return val; }
    
    private:
        std::once_flag flag;
        T val;
    };
    
    int main() {
        SetOnce<int> so(4);
        std::cout << so.get() << '\n'; // 4
        so = 5;
        std::cout << so.get() << '\n'; // 5
        so = 6;
        std::cout << so.get() << '\n'; // still 5
    }
    

    Not sure what you'd do with such a thing, but C++11 sure is cool.