In the context of a locally defined static variable, what is the expected behaviour if an exception is thrown at variable initialization and we retry to instantiate the variable?
E.g.:
void someFunc()
{
bool initialized=false;
do
{
try
{
static SomeType throwingConstructor; //it throws the first time!
initialized=true;
}
catch(...)
{
//some other code
}
}
while(!initialized);
}
I would expect, since the stack is unwinded because of the exception, that the second time the loop is executed the variable tries to be initialized again. Nevertheless, local static variables are initialized only once, so it smells somehow undefined behaviour. What is the expected behaviour of this code fragment? Does the standard guarantee a defined behaviour in this case?
Does the standard guarantee a defined behaviour in this case?
Yes. This case is exactly mentioned in the standard. According to $6.7/4 Declaration statement [stmt.dcl]
(emphasized by me):
... all block-scope variables with static storage duration (3.7.1) or thread storage duration (3.7.2) ...
Otherwise such a variable is initialized the first time control passes through its declaration; such a variable 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 you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With