function-try-block and noexcept

假装没事ソ 提交于 2020-01-11 08:25:08

问题


For the following code

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

Visual studio 14 CTP issues the warning

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

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

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


回答1:


Or is it a bug in Microsoft compiler?

Not quite.

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):

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.



来源:https://stackoverflow.com/questions/26267331/function-try-block-and-noexcept

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!