C++ Global variables and initialization order

2019-02-20 02:00发布

Let's say, I've got a following simple code:

Main.cpp

#include "A.h"

// For several reasons this must be a global variable in the project
A a1;

int _tmain(int argc, _TCHAR* argv[])
{
    // Another stuff
    return 0;
}

A.h

#pragma once

#include <string>

class A
{
private:
    // The following works normal if we use simple types like int and etc.
    static std::string myString;

public:
    A();
};

A.cpp

#include "stdafx.h"
#include "A.h"

// This executes after A::A(), so we are losing all the modifyed content
// If we skip the ="test" part, the string is going to be empty
std::string A::myString = "test";

A::A()
{
    // Here myString == ""
    myString += "1";
}

The problem is obvious: I cannot use static variables in a constructor of class A in this case as they don't save the changes. Although I need them in order to process some data.

Please, suggest me a solution.

1条回答
女痞
2楼-- · 2019-02-20 02:22

It sounds like you are trying to force the initialization of the static to happen before the constructor is called. The last time I encountered this problem, the only reliable fix was to wrap the static inside a function.

Change the declaration to a function returning reference to string.

static std::string& myString();

Change the definition to a function like this:

std::string& A::myString() {
     static std::string dummy = "test";
     return dummy;
}

Change your constructor to say:

myString() += "1";

I do not currently have an MSFT compiler handy, so you may have to tweak this a little bit, but this basically forces on-demand initialization of static.

Here is a very short test programming demonstrating how this works:

#include <string>
#include <stdio.h>


std::string& myString() {
     static std::string dummy = "test";
     return dummy;
}

int main(){
    myString() += "1";
    printf("%s\n", myString().c_str());
}
查看更多
登录 后发表回答