C++ 调用函数时,开关“控制转移绕过”的初始化

C++ 调用函数时,开关“控制转移绕过”的初始化,c++,function,switch-statement,C++,Function,Switch Statement,当我尝试构建以下开关时,我获得了一个控制权转移,绕过了:error的初始化: 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 = Main

当我尝试构建以下开关时,我获得了一个控制权转移,绕过了:error的初始化:

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
}

这与我调用枚举函数有关。如果不允许从交换机内调用函数,那么对于这类问题是否有解决办法?

< P>第6节:C++标准: goto语句是无条件的 将控制转移到语句 由标识符标记。这个 标识符应为标签6.1 位于当前功能中

第6.7节C++标准:

有可能转移到一个 阻止,但不是以绕过的方式 带有初始化的声明。A. 从一点跳转的程序 其中一个局部变量具有自动 存储持续时间不在的范围内 它在范围内的点是 除非变量具有POD,否则格式不正确 类型3.9,声明时没有 初始值设定项

我增加了重点。因为切换实际上是伪装的,所以您会遇到这种行为。要解决此问题,如果必须使用开关,请添加大括号

虽然我不清楚在交换机中创建windows向量希望实现什么,所以您可能需要重新考虑您的设计。注意:我在windows中添加了一个常量限定符,因为在您的示例中它没有被修改。

开关本质上是一个转到,也就是说,它是到相应标签的转到。C++标准禁止GOTO绕过非POD对象的初始化。将向量声明放在大括号中,它将解决问题

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

非常感谢。正如你提到的,这是一个goto,因为我正在尝试学习一些正确的编程,我想我会使用Sam Miller建议的if-else-if块。谢谢你的回答,昨天有点晚了,所以我将错误的函数调用复制到交换机中,真正的函数调用更有意义;-。尽管如此,我还是会使用建议的else if循环。你引用的C++标准的官方来源是什么?@ LUPI ISO C++标准,我在一段时间前买了一份。@ SamMiller:你能用简单的术语解释为什么在某些交换情况下需要撑杆吗?我在一个switch案例中创建了一个新对象,但是如果我声明或初始化一个普通变量,比如int,我得到了编译器错误。我没有得到任何错误。从技术上讲,if和else也是伪装的。或者,在汇编中,所有的控制语句都被伪装成jmp。但是,由于您使用大括号,它的效果与在case语句周围放置大括号相同。
if (retrycancel == 4) {
    const std::vector<MainHandles::window_data> windows(
        MainHandles().enum_windows().get_results()
    );
} else if (retrycancel == 2)
    // code
} else {
    ...
}
switch (retrycancel)
    {
     case 4:                //The user pressed RETRY
     {
        std::vector<MainHandles::window_data> windows = MainHandles().enum_windows().get_results(); //Enumerate all visible windows and store handle and caption in "windows"
        break;
     }
    case 2: 
        //code
    }