gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 14:01:18 24 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
}

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

最佳答案

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/5136295/

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