简体   繁体   中英

C++ Global variables and initialization order

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;
}

Ah

#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.

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());
}

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