开关“控制的转移绕过初始化:"调用函数时

2022-01-19 00:00:00 function switch-statement c++

当我尝试构建以下开关时,出现控制转移绕过初始化:"错误:

I get a "transfer of control bypasses initialization of:" error when i try to build the following switch:

switch (retrycancel)
{
    case 4:    //The user pressed RETRY
        //Enumerate all visible windows and store handle and caption in "windows"
        std::vector<MainHandles::window_data> windows = MainHandles().enum_windows().get_results(); 
        break;

    case 2: 
        //code
}

这与我调用枚举函数有关.如果不允许在 switch 内调用函数,是否有解决此类问题的方法?

It has something to do with my calling my enumerate function. If it is not allowed to call a function from within a switch, is there a workaround for this kind of problem?

推荐答案

C++ 标准第 6.6.4 节:

section 6.6.4 of the C++ standard:

goto 语句无条件将控制权转移到语句由标识符标记.这标识符应为标签 (6.1)位于当前函数中.

The goto statement unconditionally transfers control to the statement labeled by the identifier. The identifier shall be a label (6.1) located in the current function.

C++ 标准第 6.7 节:

section 6.7 of the C++ standard:

可以转入阻止,但不会以绕过的方式带有初始化的声明.一个从一个点跳转的程序其中具有自动的局部变量存储期限不在范围内它在范围内的点是病态的,除非变量有 POD类型 (3.9) 并且声明时没有初始化器

It is possible to transfer into a block, but not in a way that bypasses declarations with initialization. A program that jumps from a point where a local variable with automatic storage duration is not in scope to a point where it is in scope is ill-formed unless the variable has POD type (3.9) and is declared without an initializer

重点由我添加.由于 switch 实际上是 goto 变相的,因此您会遇到这种行为.要解决这个问题,如果必须使用 switch

Emphasis added by me. Since switch is really goto in disguise, you're encountering this behavior. To solve this, add braces if you must use a switch

switch (retrycancel)
    {
    case 4:
    {
        const std::vector<MainHandles::window_data> windows(
            MainHandles().enum_windows().get_results()
        );
        break;
    }
    case 2: 
        //code
    }

或重构为if/else

if (retrycancel == 4) {
    const std::vector<MainHandles::window_data> windows(
        MainHandles().enum_windows().get_results()
    );
} else if (retrycancel == 2)
    // code
} else {
    ...
}

虽然在 switch 中创建 windows vector 对我来说并不明显,但你可能想要重新思考你的设计.注意我在 windows 中添加了一个 const 限定符,因为它在您的示例中没有被修改.

Though it's not obvious to me what you're hoping to accomplish with creating the windows vector inside a switch, so you may want to rethink your design. Note I added a const qualifier to windows since it's not modified in your example.

相关文章