0

以下のコードを使用すると、静的オブジェクトの順序作成の問題が発生します。

h1.hpp

namespace X {

   struct XX {
        static const string str1;
        static const string str2;
   };
}

h1.cpp

namespace X {

        const string XX::str1 = "Hello World";
        const string XX:str2  = "Hello Country";
    }

h2.cpp ----> included h1.hpp
h3.cpp ----> included h1.hpp
h4.cpp ----> included h1.hpp
------

[X::XX::str1] としてアクセスしたい

func1(X::XX::str1); etc.

X::XX::str1 にアクセスしようとすると、「Hello World」ではなく空になります。ローカル コピーが作成されたすべての場所ではなく、同じオブジェクト (X::XX:str1) が使用されていることを確認するにはどうすればよいですか。

更新情報:

実際に X::XX::str1 プログラムにアクセスすると segfaults が発生します。オブジェクトは作成されませんか?

4

1 に答える 1

1

これはうまくいくはずです。func1別の静的オブジェクトのコンストラクターから呼び出す場合にのみ、静的順序の初期化の問題が発生する可能性があります。

この場合、静的変数へのアクセスはXX、関数ローカル静的変数への参照を返す静的メンバー関数を介して行うことができます。関数を呼び出すと、オブジェクトが初期化されることが保証されます。

#include <iostream>
#include <string>

struct XX {
  static std::string& str1() 
  { static std::string x = "Hello World"; return x; }
  static std::string& str2() 
  { static std::string x = "Hello Country"; return x; }
};

int main()
{
  std::string& x = XX::str1();
  std::cout << x << std::endl;
  std::cout << XX::str2() << std::endl;

  return 0;
}
于 2013-05-12T13:15:15.350 に答える