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.
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.
Change the definition to a function like this:
Change your constructor to say:
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: