throwing exceptions out of a destructor

后端 未结 16 1846
暗喜
暗喜 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:18

    Everyone else has explained why throwing destructors are terrible... what can you do about it? If you're doing an operation that may fail, create a separate public method that performs cleanup and can throw arbitrary exceptions. In most cases, users will ignore that. If users want to monitor the success/failure of the cleanup, they can simply call the explicit cleanup routine.

    For example:

    class TempFile {
    public:
        TempFile(); // throws if the file couldn't be created
        ~TempFile() throw(); // does nothing if close() was already called; never throws
        void close(); // throws if the file couldn't be deleted (e.g. file is open by another process)
        // the rest of the class omitted...
    };
    

提交回复
热议问题