静态const字符串将不会被初始化 [英] Static const string won't get initialized
问题描述
我有一些静态const字符串作为我的C ++类的私有成员。我知道.h中的声明和.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()
{
//使用m_data这里
}
解决方案您的TEST类型的对象是全局的吗?
$ b即
int main()
{
std :: cout< Main Entered<< std :: endl;
Test t; //这应该工作
}
测试plop; //这可能不工作取决于
解决方案是使用静态方法来获取字符串: / p>
class Test
{
static std :: string const& getData()
{
static std :: string const data(PLOP);
return data;
}
// STUFF
//删除此行
// static const std :: string m_data;
Test :: Test()
{
std :: cout< Test :: Test()< std :: endl;
Utility();
}
};
//如果在Main Entered之前打印Test :: Test()
//您的代码有潜在的问题。
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 constructor I invoke a function that uses these static strings. Surprisingly when in constructor, the strings remain uninitialized (empty strings) which is creating a problem.
Can somebody point out what might be going wrong here? I work with such usage of static const strings all the time but never ran into such situations.
Update: m_data remains empty in utility(). I have a Test class object as a private member of another class.
Here is a kind of code I am using:
// 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 }
解决方案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.
这篇关于静态const字符串将不会被初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!