C++ 全局变量和初始化顺序

标签 c++ initialization global-variables global

比方说,我有以下简单代码:

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/

相关文章:

c++ - 重载构造函数的调用不明确

c++ - 使用 void 函数在 C++ 中增加一个变量

java - java.util.function.Supplier 的 C++ 等价物是什么?

c++ - 如何将大小为 64 的字节数组转换为 Arduino C++ 中的 double 值列表?

list - 带有委托(delegate)构造函数的构造函数初始化列表执行顺序

c++ - 在 C++ 中通过重载构造函数初始化未知类型的变量

c - float 结果不正确

C++:组织程序子系统的正确方法是什么?

JavaScript : The global variables value cannot be changed

C: 函数可以返回一个全局变量吗?