C++ 异常“跳过"MSVC x64 中的 Try-Catch 子句 [英] C++ Exception "Skips" Try-Catch Clause in MSVC x64

查看:25
本文介绍了C++ 异常“跳过"MSVC x64 中的 Try-Catch 子句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用 C++ 编写程序.该程序在 Win32 (x86) 上运行良好,最近我尝试为 x64 本地编译它.当然,事情并没有立即奏效.

I'm writing a program in C++. The program has been working fine for Win32 (x86), and recently I've tried compiling it natively for x64. Of course, stuff didn't work right away.

调试问题后,我设法用这个简单的代码片段重现了它:

After debugging the problem, I've managed to reproduce it with this simple code snippet:

class MyException { };

int main()
{
    try {
        for (;;) {
            try {
                std::cout << "Throwing" << std::endl;

                throw MyException();

                if (1 == 0) {
                    continue;
                }
            } catch (const MyException&) {
                std::cout << "Catch 1" << std::endl;
            }
        }
    } catch (const MyException&) {
        std::cout << "Catch 2" << std::endl;
    }

    std::cout << "Done" << std::endl;

    return 0;
}

(我将很快解释if (1==0)子句)

使用 MSVC for x86 编译此代码时(我使用的是 2010),结果如预期:

When compiling this code using MSVC for x86 (I've used 2010), the result is as expected:

Throwing
Catch 1
Throwing
Catch 1
Throwing
Catch 1
Throwing
Catch 1
...

以此类推,无限循环.

但是,为 x64 编译此代码会导致:

However, compiling this code for x64 results in:

Throwing
Catch 2
Done

异常完全跳过内部 catch 子句!

The exception completely skips the inner catch clause!

这仅在我的代码中存在 if (1 ==0) 子句时发生.当我删除它时,异常会按预期在Catch 1"中捕获.

This only happens when the if (1 ==0) clause exists in my code. When I remove it, the exception is caught in "Catch 1" as expected.

我尝试过使用其他编译器:

I've tried using other compilers:

  • 这个错误也发生在 VS 2012 中.
  • MinGW 和 MinGW-w64 按预期工作.

我的问题:这是一个 MSVC 错误,还是我遗漏了 C++ 中的一些未定义行为?如果这确实是 MSVC 错误,我很想听听有关原因的一些见解.

My question: is this an MSVC bug, or is this some undefined behavior in C++ I'm missing? If this indeed is an MSVC bug, I'd love to hear some insight on the cause.

谢谢.

推荐答案

这个错误可能与编译器优化有关——有趣的是链接器在您的发布版本中崩溃(理论上完全优化会被打开).

This bug may have something to do with compiler optimization -- it's interesting that the linker crashes in your release build (when full optimization would theoretically be turned on).

您的调试版本是否完全禁用了优化 (/Od)?

Does your debug build have optimization completely disabled (/Od)?

Visual Studio 帮助还包含一个声明(在优化最佳实践"下)不鼓励在 64 位代码中使用 try/catch 块.

Visual Studio Help also contains a statement (under "Optimization Best Practices") discouraging try/catch blocks in 64-bit code.

如果您在发布版本中关闭优化,链接器不会崩溃.如果您只删除继续"语句,它也不会崩溃(但会重现不良行为).

If you turn off optimization in the release build, the linker doesn't crash. It also won't crash (but will reproduce the bad behavior) if you remove just the "continue" statement.

if (1==0) {
//continue;
}

这篇关于C++ 异常“跳过"MSVC x64 中的 Try-Catch 子句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆