简体   繁体   English

异常后重试本地静态变量初始化

[英]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? 在本地定义的静态变量的上下文中,如果在变量初始化时抛出异常并且我们重试实例化变量,那么预期的行为是什么?

Eg: 例如:

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): 根据$6.7/4 Declaration statement [stmt.dcl] (我强调):

... all block-scope variables with static storage duration (3.7.1) or thread storage duration (3.7.2) ... ...具有静态存储持续时间(3.7.1)或线程存储持续时间(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 an exception is thrown during the initialiser, the static variable is not initialised. 如果在初始化期间抛出异常,则不会初始化静态变量。

It will be initialised the next time the code flows over it. 它将在下一次代码流过它时初始化。

This is guaranteed by the standard. 这是标准的保证。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM