/Zc:gotoScope(强制 goto 范围中的一致性)

/Zc:gotoScope 编译器选项支持围绕 goto 语句执行标准 C++ 行为检查,这些语句会跳过局部变量的初始化。

语法

/Zc:gotoScope[-]

备注

/Zc:gotoScope 编译器选项围绕 goto 语句强制实施 C++ 标准行为,这些语句会跳过一个或多个局部变量的初始化。 当指定 /Zc:gotoScope 时,编译器在所有此类情况下都会发出错误 C2362/Zc:gotoScope- 放宽了此检查,但如果 goto 跳过具有不平常的析构函数的局部变量的初始化,编译器仍会发出错误。

/Zc:gotoScope- 选项的目的是帮助简化将旧代码库迁移到更一致的代码的过程。 在更新不一致的代码之前,可以使用该选项来禁止显示某些错误。

/Zc:gotoScope 编译器选项是 Visual Studio 2022 版本 17.4 中的新增功能。 选项默认处于关闭状态。 此功能由 /permissive- 选项(或隐含 /permissive- 的选项,例如 /std:c++20/std:c++latest)自动启用。 若要显式启用错误检查,请将 /Zc:gotoScope 添加到编译器命令行。 若要显式禁用此检查,请使用 /Zc:gotoScope- 选项。 /Zc:gotoScope- 必须出现在 /permissive- 选项或任何隐含 /permissive- 的选项之后。

示例

使用 /Zc:gotoScope 编译时,以下示例会生成错误消息:

int g(int*);
bool failed(int);

int f() {
    int v1;
    auto result = g(&v1);
    if (failed(result))
        goto OnError;
    int v2 = v1 + 2;
    return v2;
OnError:
    return -1;
}

/* Output:
t.cpp(9): error C2362: initialization of 'v2' is skipped by 'goto OnError'
*/

如果代码是使用 /Zc:gotoScope- 编译的,则编译器不会发出错误。

即使指定了 /Zc:gotoScope-,如果局部变量具有不平常的析构函数,编译器仍然会发出错误。 例如:

int g(int*);
bool failed(int);

class S {
public:
    S(int);
    ~S();
    int mf() const;
};

int f()
{
    int v1;
    auto result = g(&v1);
    if (failed(result))
        goto OnError;
    S s(v1);
    return s.mf();

OnError:
    return -1;
}

/* Output:
t.cpp(17): error C2362: initialization of 's' is skipped by 'goto OnError'
*/

在 Visual Studio 中设置此编译器选项

  1. 打开项目的“属性页” 对话框。 有关详细信息,请参阅在 Visual Studio 中设置 C++ 编译器和生成属性

  2. 选择“配置属性”>“C/C++”>“命令行”属性页

  3. 在“其他选项”中,添加 /Zc:gotoScope/Zc:gotoScope- 选择“确定”或“应用”以保存更改。

另请参阅

/Zc(一致性)
/permissive-
/std(指定语言标准版本)