0

我想编写一些依赖于静态变量值的代码。所以我想添加一些检查以消除从其他静态变量构造函数调用此代码的可能性。并防止静态初始化命令一劳永逸。例如:

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 的疯狂内置函数。

4

5 回答 5

3

Create a global bool flag that indicates whether main was called or not, initially false. Change it to true inside main(), and only change it there. Not an elegant solution, but a solution to a very weird problem, too.

于 2011-06-04T21:51:29.177 回答
0

i would go with this function and mainCalled is a global boolean variable what is false by default and changed to true whever main is called:

int bar()
{
    static bool called = 0;
    if (!mainCalled)
        ShowErrorMessage();
    if (called)
    {
        return -1;
    }
    called = true;
    //do somthing
    return 0;
}
于 2011-06-04T21:46:46.387 回答
0

You can simply declare a global variable int main_called = 0; before the function.

In the function you check if the variable is 0 and in main you set the variable to 1.

于 2011-06-04T21:47:25.893 回答
0

There isn't a portable way to do this. You can of course have your own global that you initialise in main and then uninitialise at the end of main (don't forget to use a constructor/destructor to ensure this works right even when an exception exits main).

On MSVC an easier but non portable way is #prgama init_seg. This gives you three pre-set phases and many more you can create yourself.

Martyn

于 2011-06-04T21:50:07.380 回答
0

对于单例模式来说,这不是一个可以检查其自身初始化的好案例吗?

于 2011-06-04T22:14:29.940 回答