2014-04-14 123 views
1

比方說,我有一個下面的簡單代碼:C++全局變量和初始化順序

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類的構造函數使用靜態變量,因爲它們不保存更改。雖然我需要它們來處理一些數據。

請給我建議的解決方案。

+0

您的問題都不明顯給我。它看起來像你的代碼會起作用,這取決於你實際上想要做什麼。 – ooga

+0

問題是它應該在輸入A :: A()之前初始化A :: myString。但事實並非如此。我在這裏談論這種設計。我需要首先使A :: myString初始化。 – MixMix

回答

2

這聽起來像你試圖強制靜態初始化發生之前調用構造函數。上一次我遇到這個問題時,唯一可靠的解決方法是將靜態包裝在函數中。

聲明更改爲返回參考字符串的函數。

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

謝謝你的解決方案! – MixMix