Hacker News new | ask | show | jobs
by MaxBarraclough 2020 days ago
> RAII can be decoupled from ctor/dtor mechanism, see Python's 'with' statement

That may be a useful language feature, but I don't count that as full RAII. I'm inclined to agree with Wikipedia's definition that the destructor must run whenever the object's lifetime ends, to count as proper RAII:

> resource deallocation (release) is done during object destruction (specifically finalization), by the destructor

As x can presumably leak from the with block of your example, it isn't full RAII. I think it's equivalent to the confusingly named using feature of C#. [0]

> throwing exceptions from ctors or, worse, dtors. Herb Sutter used to have a loooong list of what can go wrong in such situations

Thanks for the pointer ( or should that be reference? :-P ), these are an interesting read. [1][2][3]

> Explicit error codes happen to make it impossible to write ctors / dtors that can enter an error state by virtue of the fact that there is no way to return the error

Yes, but this approach detracts from the RAII somewhat, as it means the programmer must move the substantial code out of the constructor and into a post-construction initialization member-function capable of throwing. That may be a price worth paying, but I do consider it a price, as we've lost a useful invariant: we must now keep track of which instances are in the constructed-but-unready state. An unfortunate slide back toward C.

> My suspicion is that this is 50% of the reason of banning C++ exceptions in solid C++ style guides.

I suspect these weird edge-cases where intuition diverges from reality, are much of the motivation for those prohibitions, yes.

[0] https://docs.microsoft.com/en-us/dotnet/csharp/language-refe...

[1] http://www.gotw.ca/gotw/047.htm

[2] http://www.gotw.ca/gotw/066.htm

[3] (Rather more basic) https://herbsutter.com/2008/07/25/constructor-exceptions-in-...