2017-10-04 1 views
0

Static1.hpp静的変数を別の静的変数で初期化するにはどうすればよいですか?

#include <string> 
class Static1 
{ 
    public: 
     static const std::string my_string; 
}; 

Static1.cpp

#include "Static1.hpp" 
const std::string Static1::my_string = "aaa"; 

Static2.hpp

#include <string> 
class Static2 
{ 
    public: 
     static const std::string my_string; 
}; 

Static2.cpp

#include "Static2.hpp" 
const std::string Static2::my_string = Static1::my_string; 

main.cppに

#include "Static2.hpp" 
#include <iostream> 

int main(argc int, char** argv) 
{ 
    cout << to_string(Static2::my_string == "aaa") << endl; 
    return 0; 
} 

私は私のCMakeLists.txtにadd_executable(printMyString main.cpp Static2.cpp Static1.cpp)を置く場合add_executable(printMyString main.cpp Static2.cpp Static1.cpp)がそう(維持するために私のコードを簡単にするために私に

1 

の期待される動作を与えながら、私は

0 

を取得私がソースファイルを列挙する順序を追跡する必要はありません)、私は動作を得ることができる方法はありますか?Static2::my_string == "aaa"

+0

。私はそれがいくつかのCのパラダイムだと信じています。 – Ron

+2

「静的初期化順序の失敗」についてお読みください。 – nwp

+0

あなたは本当に同じ値を持つ静的変数を必要とします(私は彼らが何とかconstなのです)? – user463035818

答えて

5

static initialization order fiascoの効果があります。

通常の回避策は、静的変数をスコープ内の静的変数を持つ関数で置き換え、初期化して戻すことです。ここで


それはあなたの例のために行うことができる方法です:Live Example (order1) Live Example (order2)

class Static1 
{ 
    public: 
     static std::string my_string(); 
}; 

...

std::string Static1::my_string() 
{ 
    static const std::string my_string = "aaa"; 
    return my_string; 
} 

...

敗北の両方静的とconstの種類目的とした
class Static2 
{ 
    public: 
     static std::string my_string(); 
}; 

...

std::string Static2::my_string() 
{ 
    static const std::string my_string = Static1::my_string(); 
    return my_string; 
} 

...

std::cout << std::to_string(Static2::my_string() == "aaa") << std::endl; 
+0

スナップ!私はあなたが最初だと思っています... –

+0

@MartinBonner実際にはあなたは13秒で速かったです:-) – marcinj

+0

@MartinBonner :)グローバル変数!サイドの質問、[最初の使用時の構造](https:// isocpp。org/wiki/faq/ctors#static-init-first-on-first-use)関数にのみ適用され、変数には適用されません。 – AMA

関連する問題