我想编写一些依赖于静态变量值的代码。所以我想添加一些检查以消除从其他静态变量构造函数调用此代码的可能性。并防止静态初始化命令一劳永逸。例如:
static Foo foo = Foo();
// this function should be called ONLY from main program conrol flow
// ONLY after all static variable initialization was complete! ONLY!
int bar()
{
#ifdef _DEBUG
if(! CRT_was_initialized_and_main_function_was_called ) ShowErrorMessage();
#endif
if(foo.somefunction() == 2) return 0; else return -1;
}
//here inattentive programmer will caught error message during debug
const int barConstant = bar();
int main()
{
//now all is fine
const int barConstant = bar();
}
我该怎么做?如何检查我的函数是否在 main 函数之后被调用?
更新: Foo 对象的初始化代码非常繁重,它可能会很慢,甚至会引发异常
更新2:这样做没有生命问题。大多数情况下,bar 功能之前的注释都可以正常工作。我对某种调试检查感兴趣,以惩罚程序调试版本中粗心的程序员,而不是手动执行此操作。它可能是非标准方式,例如调用一些仅适用于 MSVC 的疯狂内置函数。