switch quot;transfer of control bypasses initialization of:quot; when calling a function(开关“控制的转移绕过初始化:调用函数时)
问题描述
当我尝试构建以下开关时,出现控制转移绕过初始化:"错误:
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.
这篇关于开关“控制的转移绕过初始化:"调用函数时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:开关“控制的转移绕过初始化:"调用函数时
基础教程推荐
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- CString 到 char* 2021-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
