Static const string won't get initialized

后端 未结 6 1649
一生所求
一生所求 2021-01-13 21:00

I have some static const strings as private members of my C++ class. I am aware of the declaration in .h and definition (and initialization) in .cpp practice. In the class c

6条回答
  •  无人共我
    2021-01-13 21:27

    Is your object of type TEST a global?

    If so you are then running into the problem with initialization order.

    ie.

    int main()
    {
        std::cout << "Main Entered" << std::endl;
        Test  t; // This should work
    }
    Test  plop; // This may not work depending
    

    The solution is to use a static method to get the string:

    class Test
    {
        static std::string const& getData()
        {
            static std::string const data("PLOP");
            return data;
        }
        // STUFF
        // Remove this line
        // static const std::string m_data;
        Test::Test()
        {
            std::cout << "Test::Test()" << std::endl;
            Utility();
        }
    };
    // If "Test::Test()" is printed before "Main Entered"
    // You have a potential problem with your code.
    

提交回复
热议问题