开关“控制权的转移绕过初始化:”当调用函数时
当我尝试构建以下开关时,出现“控制转移绕过初始化:”错误:
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
}
它与我调用枚举函数有关。如果不允许从开关内调用函数,是否有解决此类问题的方法?
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
}
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
C++ 标准第 6.6.4 节:
C++ 标准第 6.7 节:
我添加的 强调。由于
switch
实际上是变相的goto
,因此您会遇到这种行为。为了解决这个问题,如果您必须使用switch
或重构为
if
/else
,请添加大括号虽然对我来说您所希望的并不明显来完成在
switch
内创建windows
vector
,因此您可能需要重新考虑您的设计。 注意 我向windows
添加了一个const
限定符,因为它在您的示例中未进行修改。section 6.6.4 of the C++ standard:
section 6.7 of the C++ standard:
Emphasis added by me. Since
switch
is reallygoto
in disguise, you're encountering this behavior. To solve this, add braces if you must use aswitch
or refactor into
if
/else
Though it's not obvious to me what you're hoping to accomplish with creating the
windows
vector
inside aswitch
, so you may want to rethink your design. Note I added aconst
qualifier towindows
since it's not modified in your example.开关本质上是一个
goto
,也就是说,它是一个goto
到适当的标签。 C++ 标准禁止 goto 绕过非 POD 对象的初始化。将向量声明放入大括号中即可解决问题a switch is essentially a
goto
, that is, it is agoto
to the appropriate label. The C++ standard forbids a goto to bypass an initialization of a non-POD object. Take the vector declaration into braces and it will solve the problem