What's the best way to run an expensive initialization?

前端 未结 2 1924
南笙
南笙 2021-02-05 15:45

I\'ve got a singleton that is expensive to initialize:

struct X {...};

const X&
get_X()
{
    static const X x = init_X();
    return x;
}

2条回答
  •  北荒
    北荒 (楼主)
    2021-02-05 16:04

    If you don't mind the delay when your application starts, you could make x as a static private member of the class, like this

    #include 
    
    class X {
    public:
        static X const& get_x();
    private:
        static X const x;
    
        X()
        {
            std::cout << "X init" << std::endl;
        }
    };
    
    int main()
    {
        std::cout << "Enter main" << std::endl;
        X::get_x();
        return 0;
    }
    
    X const X::x;
    
    X const& X::get_x()
    {
        return X::x;
    }
    

提交回复
热议问题