gpt4 book ai didi

c++ - 调用函数时切换 "transfer of control bypasses initialization of:"

转载 作者:太空宇宙 更新时间:2023-11-04 13:40:33 26 4
gpt4 key购买 nike

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

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
}

这与我调用我的枚举函数有关。如果不允许从开关中调用函数,是否有解决此类问题的方法?

最佳答案

C++ 标准第 6.6.4 节:

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 节:

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

时添加大括号
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 限定符,因为它在您的示例中没有被修改。

关于c++ - 调用函数时切换 "transfer of control bypasses initialization of:",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27800055/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com