Timeline for answer to Avoiding throw because we are not sure the exceptions will always be caught by Kaia
Current License: CC BY-SA 4.0
Post Revisions
7 events
| when toggle format | what | by | license | comment | |
|---|---|---|---|---|---|
| Apr 28, 2024 at 7:48 | comment | added | daramarak |
@Kaia I don't disagree to this. My point was that any function that has new something(); throw somethingElse(); are bound to leak if you do not explicitly set up some way of cleaning up. Not just constructors. My main point is if you don't have extreme vigilance when writing new something will bite you. Always prefer make_unique and friends. Throwing and constructors are not what should be avoided - new is.
|
|
| Apr 22, 2024 at 22:00 | comment | added | Kaia |
@daramarak If the ctor completes, I believe it's guaranteed that the dtor will be called at the end of lifecycle, including if the object falls out of scope due to an exception and catch. So Obj a(); a.alloc(); throw myError(); should call a's dtor and free resources.
|
|
| Apr 22, 2024 at 12:08 | comment | added | daramarak | @JorisTimmermans i agree. My point was that this is not something about constructors and throwing in constructors. It is just as hard in any other context where you do resource allocation. But if your point is that exceptions make programming in C++ harder - yes it does. Exceptions require strict control of resource allocation. | |
| Apr 22, 2024 at 7:03 | comment | added | Joris Timmermans | @daramarak Yes it's a programming error, but a very easy one to make and part of the reason that doing exception handling correctly is hard. Therefore I think it's definitely worth pointing out as a "gotcha" that you need to be aware of. | |
| Apr 21, 2024 at 12:57 | comment | added | daramarak | But isn't this really a programming error when creating the constructor? Just as one have to write the destructor in a fashion that prevent leaks, you have to write the constructor in the same way? When you write "new" in your code it is about time to really be vigilant. I would say that writing "new" in one line and "throw" in a subsequent line without releasing the memory before the throw is an error in any context, not just the constructor. | |
| S Apr 20, 2024 at 0:50 | review | First answers | |||
| Apr 20, 2024 at 11:46 | |||||
| S Apr 20, 2024 at 0:50 | history | answered | Kaia | CC BY-SA 4.0 |