静态const字符串不会被初始化

3 c++ string static initialization const

我有一些静态const字符串作为我的C++类的私有成员.我知道.hpp中的声明和.cpp实践中的定义(和初始化).在类构造函数中,我调用一个使用这些静态字符串的函数.令人惊讶的是,在构造函数中,字符串保持未初始化(空字符串),这会产生问题.

有人可以指出这里可能出现的问题吗?我一直使用静态const字符串的这种用法,但从未遇到过这种情况.

更新:m_data在utility()中保持为空.我有一个Test类对象作为另一个类的私有成员.

这是我正在使用的一种代码:

// Test.h
class Test
{
public:
  Test();
private:
  void utility();

 static const std::string m_data;
};

// Test.cpp
const std::string Test::m_data = "Data";

Test::Test()
{
utility();
}

void Test::utility()
{
//use m_data here
}
Run Code Online (Sandbox Code Playgroud)

Mar*_*ork 5

你的TEST类型对象是全局的吗?

如果是这样,那么您将遇到初始化顺序问题.

即.

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

解决方案是使用静态方法来获取字符串:

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.
Run Code Online (Sandbox Code Playgroud)


dbr*_*ien 4

您是这么定义的吗?

class X
{
public:
      static string i;
};
string X::i = "blah"; // definition outside class declaration
Run Code Online (Sandbox Code Playgroud)

请参阅:静态数据成员(仅限 C++)