开发者

Function-scope static object's constructor throws an exception

Consider the following code:

#include <iostream>

struct X{
   X(){
      throw 0;
   }
};

void f(){
   static X x;
}

int main(){
   try {
      f();
   }
   catch(int)   {
      std::cout << "Caught first time" &l开发者_高级运维t;< std::endl;
   }
   try {
      f();
   }
   catch(int) {
      std::cout << "Caught second time" << std::endl;
   }
}

The output of this program is

Caught first time

Caught second time

So, is it guaranteed by the standard that the constructor of a static object is going to be called over and over again until it's successfully completed? I can't find the place in the standard where it is mentioned, so a quote or a reference to chapter and verse are very much welcome.

Or is there any undefined behavior involved in my example?


It is guaranteed that the construction will be attempted as long as it fails.

It's caused by what is stated in C++03 §6.7/4:

... Otherwise such an object is initialized the first time control passes through its declaration; such an object is considered initialized upon the completion of its initialization. If the initialization exits by throwing an exception, the initialization is not complete, so it will be tried again the next time control enters the declaration. If control re-enters the declaration (recursively) while the object is being initialized, the behavior is undefined. [Example:

int foo(int i)
{
  static int s = foo(2*i);    // recursive call – undefined
  return i+1;
}

--end example]

I will note that gcc throws an exception in case of recursive initialization attempt, see litb's related question as for my source.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜