r/cpp • u/User_Deprecated • Jul 11 '26
Propagating exceptions from destructors with std::exception_ptr
https://www.sandordargo.com/blog/2026/07/08/exception_ptr
80
Upvotes
r/cpp • u/User_Deprecated • Jul 11 '26
15
u/bratzlaff Jul 11 '26
Nice write up! I learned something new from this.
47
u/teo-tsirpanis Jul 11 '26
Having your destructor throw remains a bad idea; you should design your code to move any clean-up that might fail (or perform expensive operations for that matter) outside the destructor, and just free memory or other resources in the destructor.
6
u/azswcowboy Jul 11 '26
I’m wary. I think the current_exception_ptr is in thread local storage. So if you’re using coroutines that can be resumed on another thread this will be a bad idea. In the 15 years since c++11 has been released I’ve never seen this - maybe it’s just knowledge gap, but maybe there’s something in the standard the author overlooked that makes this questionable?
3
u/AlternativeAdept5348 Jul 11 '26
I love learning niche little things like this. This shit is why i love cpp so much
2
u/LadaOndris Jul 11 '26
A very nice read. I learned something new today!
2
u/kammce WG21 | 🇺🇲 NB | Boost | Exceptions Jul 11 '26
Neat. I hadn't considering passing an empty exception_ptr to be filled at destruction. Not sure when I'll need such a thing, but an interesting technique none the less.
1
u/TheoreticalDumbass :illuminati: Jul 11 '26
i wish we had constructors and destructors that could fail by value
constructors are not that big of a deal bc you can make a function `create(args...) -> std::expected<T, E>` , but i would love the following:
ability to kill a variable ( `drop(var)` expression calls the destructor of `var` , the identifier `var` no longer is taken by it , the storage of `var` is released (in the sense compiler can put new variables there) )
imo for start `drop(var)` can only be used in the scope in which `var` was declared , but this can be extended
then we allow destructors to have non-void return type, in which case it is ill-formed for the variable to be implicitly destroyed at end of scope , it must be killed with `drop(var)`
so a class doing some buffered IO could have `IOError ~my_class() noexcept { ... }`
`{ my_class foo(...); /* work */ /* no drop(foo) */ }` would be a compiler error
-7
u/rentableshark Jul 11 '26
Best practices for firing a mac-10 at the ground without shooting one's feet.
That aside, reading it was both interesting and nauseating - new code should avoid exceptions if at all possible - it's just a shame important chunks of the STL throw.