C ++全局变量和初始化顺序 [英] C++ Global variables and initialization order

查看:161
本文介绍了C ++全局变量和初始化顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

问题很明显:在这种情况下,我不能在A类的构造函数中使用静态变量,因为它们不保存更改.尽管我需要它们才能处理一些数据.

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

我目前没有手持MSFT编译器,因此您可能需要稍作调整,但这基本上会强制按需初始化static.

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

这篇关于C ++全局变量和初始化顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆