【问题标题】:static variables initialization order between many classes许多类之间的静态变量初始化顺序
【发布时间】:2011-04-20 08:04:59
【问题描述】:
c.h   
class C{  
    static string s;  
}

c.cpp  
string C::s=D::staticMethod();

d.h  
class D{  
static string s;  
static string staticMethod();  
}

d.cpp  
string D::s("some string");  
string D::staticMethod(){  
    return s;  (***)  
}

这不行,它在 (*) 处停止,因为 D::s 尚未初始化。有什么方法可以在 c.cpp 之前编译 d.cpp?

【问题讨论】:

  • @Asher:可悲的是,它确实可以编译,但有未定义的运行时行为。更糟糕的是,在实践中,它有 50-50 的机会成功运行,这使得 bug 更难追踪。
  • 知道顺序的唯一方法是对象是否在同一个 .cpp 文件中。否则,它可能会在不同的构建之间有所不同。
  • @Mike:哦,对了。我将“它在 () 处停止”读作“编译器在 () 处停止”。我知道运行时行为是未定义的,但我认为他找到了一个可以捕获它的编译器。我想这对我来说太乐观了——编译器至少会警告这种事情吗?它应该是可检测的(“这个 cpp 文件是否使用了另一个定义的静态文件?”)。

标签: c++ static-methods static-members


【解决方案1】:

恕我直言的最佳参考:

What's the "static initialization order fiasco"?

【讨论】:

    【解决方案2】:

    简而言之,不。如果您真的需要这种行为,请查看 Singleton 模式。但也要仔细考虑您的应用程序中是否需要这种耦合。

    【讨论】:

      猜你喜欢
      • 2018-12-19
      • 2010-09-17
      • 2015-06-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多