在 C++ 中如何使用 goto 语句销毁变量?

How does happen the destruction of variables with a goto statement in C++?

#include <iostream>
using namespace std;
int main() {
    if (true) {
        int b = 3;
    label_one:
        cout << b << endl;
        int j = 10;
        goto label_one;
    }
}

上面代码中goto跳转到label_one,使得变量j在每次循环中被销毁和重建。但是 b 变量会发生什么?它是否也被摧毁和重建,还是从未被摧毁?根据 C++ ISO:

Transfer out of a loop, out of a block, or back past an initialized variable with automatic storage duration involves the destruction of objects with automatic storage duration that are in scope at the point transferred from but not at the point transferred to.

我的解释是 if 范围内的所有变量都应该被销毁,但如果是这样,它们什么时候重新初始化(我代码中的变量 b)?

正如引用的文字所说,只有当变量在 goto 语句的范围内时,它才会在 goto 期间被销毁,但 不会 [=17] =] 在目标标签的范围内。 b 在两个点都在范围内,所以它没有被销毁。只有j被销毁。

这很容易测试。

#include <iostream>
using namespace std;
class X
{
    public:
        X()     {std::cout << "C\n";}
        ~X()    {std::cout << "D\n";}
};

int main() {
    if (true) {
        int b = 3;
label_one:
        cout << b << endl;
        X j;
        if (b >= 5) {
            return 0;
        }
        ++b;
        std::cout << "GOTO\n";
        goto label_one;
    }
}

编译并运行:

> g++ -std=c++17 ty.cpp
> ./a.out
3
C
GOTO
D
4
C
GOTO
D
5
C
D

您唯一需要考虑的是“Destory”在“int”而不是 class 类型的上下文中的含义。基本上对于一个整数,这是一个空操作。