比方说,我有以下简单的代码:
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";
}
问题很明显:在这种情况下,我不能在类 A 的构造函数中使用静态变量,因为它们不保存更改。虽然我需要它们来处理一些数据。
请给我建议一个解决方案。
听起来您正在尝试强制静态初始化发生before构造函数被调用。上次我遇到这个问题时,唯一可靠的解决方法是将 static 包装在函数中。
将声明更改为返回字符串引用的函数。
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());
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)