Noexcept promise to the constructor of the derived class: can this be used without the noexcept promise in the base constructor?

Say I have a class

class C : public B { public: C() noexcept; } 

Does the noexcept specifier noexcept the same promise with the base class? That is, when I consider the possibility of using noexcept, I just look at the behavior of C :: C () or do I also need to consider whether B :: B () can throw exceptions?

For example, if B :: B throws an exception, does this apply to C :: C or to code requesting a new instance of the class? - If you extend to C :: C, this will be one of the reasons to avoid noexcept for the constructor if the base class is no exception to the constructor.

+7
c ++ exception c ++ 11
source share
1 answer

There is a technical requirement that the constructor of the base class be not declared noexcept, but it should not be thrown when called by a derived constructor that is declared noexcept.

So, yes, you need to think about whether the base class constructor can throw (exceptions or otherwise).

I think the best way to ask my question is: where is the next exception?

Calls are made as follows:

 caller -> derived constructor (the noexcept applies to this) -> subobject constructors (includes bases) - derived constructor body (not a call, but part of the derived constructor that is executed after the subobjects are constructed) 

So, if a subobject (whether basic or elemental) generates a browser, it first passes to the derived constructor, which cannot and cannot †† swallow the exception, so it will apply to the caller if the constructor was not superfluous. But since it is, std::terminate called.

If the base does not throw away as required by the derivative, then it satisfies the requirement and can itself be declared noexcept, so there is a rare reason not to do this. Perhaps if the base class is part of a library that should support C ++ 03, while the derived class can adopt a later standard, that makes sense.

†† It can catch using the try-block function, but they will always throw again.

+6
source share

All Articles