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?
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:
I will note that gcc throws an exception in case of recursive initialization attempt, see litb’s related question as for my source.