简体   繁体   English

如何用另一个静态变量初始化一个静态变量?

[英]How to initialize a static variable with another static variable?

Static1.hpp 静态1.hpp

#include <string>
class Static1
{
    public:
        static const std::string my_string;
};

Static1.cpp 静态1.cpp

#include "Static1.hpp"
const std::string Static1::my_string = "aaa";

Static2.hpp 静态2.hpp

#include <string>
class Static2
{
    public:
        static const std::string my_string;
};

Static2.cpp 静态2.cpp

#include "Static2.hpp"
const std::string Static2::my_string = Static1::my_string;

main.cpp main.cpp

#include "Static2.hpp"
#include <iostream>

int main(argc int, char** argv)
{
     cout << to_string(Static2::my_string == "aaa") << endl;
     return 0;
}

If I put add_executable(printMyString main.cpp Static2.cpp Static1.cpp) in my CMakeLists.txt, I get 如果我在CMakeLists.txt中放入add_executable(printMyString main.cpp Static2.cpp Static1.cpp) ,我会得到

0

while add_executable(printMyString main.cpp Static2.cpp Static1.cpp) gives me the expected behavior of add_executable(printMyString main.cpp Static2.cpp Static1.cpp)为我提供了预期的行为

1

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" ? 为了使我的代码更易于维护(这样就不必跟踪列出我的源文件的顺序),有什么方法可以确保我得到Static2::my_string == "aaa"

You are experiencing effects of a static initialization order fiasco . 您正在经历static初始化顺序失败的影响

The usual work-around is to substitute your static variables with functions that have a static variable in the scope, initialize, and return it. 通常的解决方法是用范围内具有静态变量的函数替换静态变量,然后初始化并返回它。


Here is how it could be done for your example: Live Example (order1) Live Example (order2) 下面是它可以为你的例子来完成: 活生生的例子(order1) 活生生的例子(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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM