Try catch syntax constructor

前端 未结 2 685
温柔的废话
温柔的废话 2021-01-12 11:58

http://ideone.com/UtVzxw

struct base
{
    base() { throw std::exception(); }
};

struct derived : public base
{
    derived() try : base()  { }

    catch (         


        
2条回答
  •  执念已碎
    2021-01-12 12:01

    function-try-block in the constructor doesn't prevent the exception from being thrown. Here's an excerpt from C++ standard draft N4140, [except.handle]:

    14 If a return statement appears in a handler of the function-try-block of a constructor, the program is ill-formed.

    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. Otherwise, ...

    The reason for this is that if base class or any member constructor throws an exception, then the construction of the whole object fails, and there's no way to fix it, so the exception has to be thrown.

    There's a GOTW on this, and the bottomline is

    Constructor function-try-block handlers have only one purpose -- to translate an exception. (And maybe to do logging or some other side effects.) They are not useful for any other purpose.

    So, yes, your last code sample is perfectly fine.

提交回复
热议问题