功能尝试块和noexcept [英] function-try-block and noexcept

查看:153
本文介绍了功能尝试块和noexcept的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于以下代码

struct X
{
    int x;
    X() noexcept try : x(0)
    {
    } 
    catch(...)
    {
    }
};

Visual Studio 14 CTP发出警告

Visual studio 14 CTP issues the warning

警告C4297:'X :: X':该函数假定不会引发异常,但会引发异常

warning C4297: 'X::X': function assumed not to throw an exception but does

注意:__declspec(nothrow),throw(),noexcept(true)或noexcept是 在功能上指定

note: __declspec(nothrow), throw(), noexcept(true), or noexcept was specified on the function

这是对noexcept的滥用吗?还是Microsoft编译器中的错误?

Is this a misuse of noexcept? Or is it a bug in Microsoft compiler?

推荐答案

还是Microsoft编译器中的错误?

Or is it a bug in Microsoft compiler?

不太.

像这样的所谓的function-try-block不能防止异常会传到外面.考虑到对象永远不会完全构造,因为构造函数无法完成执行. catch块必须抛出其他内容,否则当前异常将被抛出([except.handle]/15):

A so-called function-try-block like this cannot prevent that an exception will get outside. Consider that the object is never fully constructed since the constructor can't finish execution. The catch-block has to throw something else or the current exception will be rethrown ([except.handle]/15):

如果控制到达末尾,则当前处理的异常被重新抛出 构造函数的 function-try-block 的处理程序的名称,或 破坏者.

The currently handled exception is rethrown if control reaches the end of a handler of the function-try-block of a constructor or destructor.

因此,编译器推断出构造函数确实可以抛出异常.

Therefore the compiler deduces that the constructor can indeed throw.

struct X
{
    int x;
    X() noexcept : x(0)
    {
        try
        {
            // Code that may actually throw
        }
        catch(...)
        {
        }
    } 
};

应在没有警告的情况下进行编译.

Should compile without a warning.

这篇关于功能尝试块和noexcept的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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