如何用另一个静态变量初始化一个静态变量? [英] How to initialize a static variable with another static variable?
问题描述
Static1.hpp
Static1.hpp
#include <string>
class Static1
{
public:
static const std::string my_string;
};
Static1.cpp
Static1.cpp
#include "Static1.hpp"
const std::string Static1::my_string = "aaa";
Static2.hpp
Static2.hpp
#include <string>
class Static2
{
public:
static const std::string my_string;
};
Static2.cpp
Static2.cpp
#include "Static2.hpp"
const std::string Static2::my_string = Static1::my_string;
main.cpp
#include "Static2.hpp"
#include <iostream>
int main(argc int, char** argv)
{
cout << to_string(Static2::my_string == "aaa") << endl;
return 0;
}
如果我在CMakeLists.txt文件中放入 add_executable(printMyString main.cpp Static2.cpp Static1.cpp)
,我会得到
If I put add_executable(printMyString main.cpp Static2.cpp Static1.cpp)
in my CMakeLists.txt, I get
0
而 add_executable(printMyString main.cpp Static2.cpp Static1.cpp)
给了我预期的行为
1
为了使我的代码易于维护(这样就不必跟踪列出我的源文件的顺序),有什么方法可以确保我得到 Static2 ::my_string =="aaa"
?
To make my code easier to maintain (so that I don't need to keep track of the order I list my source files), is there any way I can ensure that I get the behavior where Static2::my_string == "aaa"
?
推荐答案
您正在体验 静态
初始化顺序惨败.
You are experiencing effects of a static
initialization order fiasco.
通常的解决方法是将静态变量替换为作用域中具有静态变量的函数,然后初始化并返回它.
The usual work-around is to substitute your static variables with functions that have a static variable in the scope, initialize, and return it.
以下是您的示例的操作方法: 实时示例(order1) 实时示例(order2)
Here is how it could be done for your example: Live Example (order1) Live Example (order2)
class Static1
{
public:
static std::string my_string();
};
...
std::string Static1::my_string()
{
static const std::string my_string = "aaa";
return my_string;
}
...
class Static2
{
public:
static std::string my_string();
};
...
std::string Static2::my_string()
{
static const std::string my_string = Static1::my_string();
return my_string;
}
...
std::cout << std::to_string(Static2::my_string() == "aaa") << std::endl;
这篇关于如何用另一个静态变量初始化一个静态变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!