c++ - 无法访问 C++ 中全局变量的构造函数中的静态(非原始)成员

标签 c++ constructor stl initialization global-variables

以下代码在使用例如时可以正常工作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 非局部变量的初始化)

  1. ...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/

相关文章:

c++ - 基类和派生类中的构造函数

c++ - 如何用空格替换 std::string 中的所有非字母字符(数字和特殊字符)

c++ - 多重集 STL 无法识别的查找函数

C++ 组合,一个对象如何知道它所在的类?

swift - 为什么 swift 同时提供 CGRect 初始化器和 CGRectMake 函数?

c++ - Buit Rectangles(我自己的类型),不会随窗口调整大小?

javascript - 如果不重新分配构造函数,我们如何在函数上使用 'new'

c++ - 具有来自 STL 的 vector 、列表或映射作为成员的类是否需要复制构造函数

c++ - 调用execvp()后主窗口关闭

c++ - 从 C++ 中的文本文件中读取带有杂散空格的逗号分隔值