以下代码在使用例如时可以正常工作int 而不是 std::string、std::map 等
我有一个全局变量,在使用默认构造函数时需要静态成员的条目,但这里的字符串为空。变量“test”不必位于类本身内部。我认为 STL 组件(或非基元)涉及一些初始化顺序问题。使用 C++14。
// MyClass.h
#include <string>
class MyClass{
public:
static const std::string test;
MyClass();
};
// MyClass.cpp
#include <iostream>
#include "MyClass.h"
const std::string MyClass::test = "Yooooooo";
MyClass::MyClass(){
std::cout << test << std::endl;
}
// main.cpp
#include <iostream>
#include "MyClass.h"
const MyClass c;
int main(){
//MyClass c; // Would work
std::cout << "There should be something above this line." << std::endl;
}
最佳答案
具有静态存储持续时间的对象在不同编译单元中相对于彼此初始化的顺序是无序的。
来自 C++ 14 标准(3.6.2 非局部变量的初始化)
- ...Otherwise, the initialization of a variable is indeterminately sequenced with respect to the initialization of a variable defined in a different translation unit.
您有两个变量,它们在不同的编译单元中具有静态存储持续时间
const std::string MyClass::test = "Yooooooo";
和
const MyClass c;
您可以通过使用内联说明符声明变量来避免该问题。
class MyClass {
public:
inline static const std::string test = "Yooooooo";
MyClass();
};
关于c++ - 无法访问 C++ 中全局变量的构造函数中的静态(非原始)成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71369225/