What is the rationale for not having static constructor in C++?

后端 未结 5 1504
长情又很酷
长情又很酷 2020-12-24 12:38

What is the rationale for not having static constructor in C++?

If it were allowed, we would be initializing all the static members in it, at one place in a very org

5条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-24 12:50

    You could get by with putting your "static" members in their own class with their own constructor that performs their initialization:

    class StaticData
    {
        int some_integer;
        std::vector strings;
    
    public:
        StaticData()
        {
           some_integer = 100;
           strings.push_back("stack");
           strings.push_back("overflow");
        }
    }
    
    class sample
    {    
        static StaticData data;
    
    public:
        sample()
        {
    
        }
    };
    

    Your static data member is guaranteed to be initialized before you first try to access it. (Probably before main but not necessarily)

提交回复
热议问题