Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retry local static variable initialization after exception

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?

like image 470
Alex Gidan Avatar asked Jan 07 '23 08:01

Alex Gidan


1 Answers

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.

like image 177
songyuanyao Avatar answered Jan 08 '23 22:01

songyuanyao