Why custome deleters for smart pointers are not allowed to throw exceptions?

93 Views Asked by At

I'm reading about smart pointers from a book and there it is specified that custom deleter is not allowed to throw. But I could not figure out the reason for this. Why they are not allowed to throw?

1

There are 1 best solutions below

5
Caleth On BEST ANSWER

The deleter held by a smart pointer is expected to run when the smart pointer is destructed, which might be during the stack unwinding between a throw and a catch.

If your deleter throws in that circumstance, and it isn't caught by the smart pointer's destructor, then to avoid two exceptions being in-flight at the same time, there is a language rule to std::terminate the process.

The specific case of std::unique_ptr and std::shared_ptr do have a precondition that the deleter must never throw when they call it, under pain of undefined behaviour, but they don't require it to be marked noexcept.