c++constructorconstantslazy-evaluation

Lazy initialization of const attributes in c++


I would like to carry out a lazy initialization of a set of (std::vector) attributes in c++. They have to be const, in the sense that after the first time they are initialized (via a get method), their values cannot be modified. What is the cleanest way to do this?

I tried to define the attributes as const, but in this way they must be initialized in the construntor initialization list, so no lay initialization seems to be possible.


Solution

  • You might do something like:

    class MyClass
    {
    public:
        const std::vector<int>& getV()
        {
            if (!v) {
                v = std::vector{4, 8, 15, 16, 23, 42};
            }
            return *v;
        }
    private:
        std::optional<std::vector<int>> v;
    };
    

    If some specific value is "prohibited" from vector (as empty vector), you might remove optional and use that value instead.