【问题标题】:namespace with static data memeber of structure aving ordering issue具有排序问题的结构的静态数据成员的命名空间
【发布时间】:2013-05-12 13:09:50
【问题描述】:

我有如下代码,我遇到了静态对象顺序创建问题。

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 程序段错误时。所以没有创建对象?

【问题讨论】:

  • 这是实际代码吗? struct 定义中缺少分号。
  • @0x499602D2 静态初始化问题通常只在涉及多个 TU 时才会出现。
  • @pmr:是的,这是我的问题,即使我创建了一个对象,这些静态成员也不会被创建,无法理解为什么和我的应用程序段错误。

标签: c++ object c++11 namespaces static-members


【解决方案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;
}

【讨论】:

    猜你喜欢
    • 2018-04-16
    • 2014-04-29
    • 2013-02-05
    • 1970-01-01
    • 1970-01-01
    • 2012-06-16
    • 1970-01-01
    • 2012-05-27
    • 2015-03-14
    相关资源
    最近更新 更多