throwing exceptions out of a destructor

后端 未结 16 1851
暗喜
暗喜 2020-11-22 00:23

Most people say never throw an exception out of a destructor - doing so results in undefined behavior. Stroustrup makes the point that \"the vector destructor e

16条回答
  •  孤独总比滥情好
    2020-11-22 01:02

    Q: So my question is this - if throwing from a destructor results in undefined behavior, how do you handle errors that occur during a destructor?

    A: There are several options:

    1. Let the exceptions flow out of your destructor, regardless of what's going on elsewhere. And in doing so be aware (or even fearful) that std::terminate may follow.

    2. Never let exception flow out of your destructor. May be write to a log, some big red bad text if you can.

    3. my fave : If std::uncaught_exception returns false, let you exceptions flow out. If it returns true, then fall back to the logging approach.

    But is it good to throw in d'tors?

    I agree with most of the above that throwing is best avoided in destructor, where it can be. But sometimes you're best off accepting it can happen, and handle it well. I'd choose 3 above.

    There are a few odd cases where its actually a great idea to throw from a destructor. Like the "must check" error code. This is a value type which is returned from a function. If the caller reads/checks the contained error code, the returned value destructs silently. But, if the returned error code has not been read by the time the return values goes out of scope, it will throw some exception, from its destructor.

提交回复
热议问题