功能尝试块和noexcept

功能尝试块和noexcept

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

问题描述

对于以下代码

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

Visual Studio 14 CTP发出警告

Visual studio 14 CTP issues the warning

注意:__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?

推荐答案

不太.

像这样的所谓的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):

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

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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-22 19:20