问题
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