比方说,我有以下简单代码:
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;
}
啊啊
#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";
}
问题很明显:在这种情况下,我不能在类 A 的构造函数中使用静态变量,因为它们不保存更改。尽管我需要它们来处理一些数据。
请给我一个解决方案。
最佳答案
听起来您正试图强制在调用构造函数之前 进行静态初始化。上次我遇到这个问题时,唯一可靠的解决方法是将静态包装在一个函数中。
将声明更改为返回字符串引用的函数。
static std::string& myString();
将定义更改为这样的函数:
std::string& A::myString() {
static std::string dummy = "test";
return dummy;
}
改变你的构造函数说:
myString() += "1";
我目前手边没有 MSFT 编译器,因此您可能需要稍微调整一下,但这基本上会强制按需初始化静态。
这是一个非常简短的测试程序,演示了它是如何工作的:
#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());
}
关于C++ 全局变量和初始化顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23050334/