Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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" << 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?

like image 957
Armen Tsirunyan Avatar asked Aug 08 '11 12:08

Armen Tsirunyan


1 Answers

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.

like image 187
Matthieu M. Avatar answered Oct 13 '22 00:10

Matthieu M.