简体   繁体   中英

No access to static (non-primitive) members in constructor of global variable in C++

The following code works fine when using eg int instead of std::string, std::map etc.

I have a global variable that needs an entry of the static member when using the default constructor, but this string is empty here. The variable "test" does not have to be inside the class itself. I think there is some initialization order problem involved with STL components (or non-primitives). Using 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;
}

The order in which objects with the static storage duration are initialized in different compilation units relative to each other is unsequenced.

From the C++ 14 Standard (3.6.2 Initialization of non-local variables)

  1. ...Otherwise, the initialization of a variable is indeterminately sequenced with respect to the initialization of a variable defined in a different translation unit.

You have two variables with static storage duration in different compilation units

const std::string MyClass::test = "Yooooooo";

and

const MyClass c;

You could avoid the problem by declaring the variable with the inline specifier.

class MyClass {
public:
    inline static const std::string test = "Yooooooo";
    MyClass();
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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