r/cpp • • Jul 11 '26

Propagating exceptions from destructors with std::exception_ptr

https://www.sandordargo.com/blog/2026/07/08/exception_ptr
80 Upvotes

41 comments sorted by

View all comments

Show parent comment

4

u/azswcowboy Jul 11 '26

Thanks /u/kammce ! Was hoping you’d appear - since I’m pretty sure you know more about this than basically anyone except maybe a few compiler writers :)

So if the only try/catch is local the pointer might be invalidated - but if the thread constructor has an exception handler of last resort then it would remain valid? Still if the thread is destroyed the TLS will be gone — so one would need to be careful if that can happen.

7

u/kammce WG21 | 🇺🇲 NB | Boost | Exceptions Jul 11 '26

Im pretty sure it's UB to kill a thread that hasn't finished. If your thread is currently within a catch block, then it's at that point where it needs to use current_exception and get a copy of the exception_ptr. Once you have e that copy, you have ref_count = 2, and when the code exits the catch block, you now have ref_count = 1, because the TLS slot got wiped out. If you pass that ptr to another thread, somehow, it'll have access to that exception. From there, if your thread exits and then is destroyed, that's fine, the TLS slot for the current exception wasn't being used anymore anyway.

4

u/azswcowboy Jul 11 '26

Thanks, maybe this better than I thought. Some experiments are in order. As usual, appreciate the insights.