C++ throwing exceptions from constructors and destructors

preview_player
Показать описание

When an exception is thrown from constructor, stack unwinding begins: destructors for objects with automatic storage duration from constructor’s block, members and bases of the class are called in the reverse order of their constructions. However, object creation is not done and thus its lifetime has started. Therefore, destructor in this case is not called (except when using delegating constructor). Remember about this when you allocate some resource in potentially throwing constructor and deallocate it in destructor; and, if possible, manage only one resource in one class.

Regarding destructors, they are by default noexcept (i.e. non-throwing, we do not expect exceptions from them, std::terminate is called in case of exception going out of destructor) although we technically can throw exceptions therefrom. If destructor is declared noexcept(false), then stack unwinding will happen after an exception and we may catch it outside. But don’t do it. Destructors are by default non-throwing for a reason, and we must not throw exceptions in destructors unless we catch them inside destructor. Because destructors are called during stack unwinding when an exception is thrown, and we are not allowed to throw another exception while the previous one is not caught – in such a case std::terminate will be called as well.

C++ Core Guidelines:
- Use RAII to prevent leaks
- Never throw while being the direct owner of an object
- Destructors, deallocation, and swap must never fail
- If you can't throw exceptions, consider failing fast
- Let a constructor establish an invariant, and throw if it cannot
Рекомендации по теме
Комментарии
Автор

Very clear explanation, really informative

alexdai_
Автор

Ай джаст фасинейтед бай йор аксент, мэн!
Сенкс фор туториал!

pro.crastination
Автор

very good but your accent or way of talking is very difficult to understand

sahil