6 ms·
What everybody seems to miss (including in the other comments here) is the fact that no kind of hackery with destructors will ever make them equivalent to scope
by mehrdadn 9y ago
What everybody seems to miss (including in the other comments here) is the fact that no kind of hackery with destructors will ever make them equivalent to scope(exit) or finally{}, because of the simple reason that destructors invoked via exceptions can't throw their own exceptions. And this makes sense, because destructors are meant to release resources, whereas finally/scope(exit) are meant to execute after prior operations in a LIFO manner. Not all operations that need to occur in a LIFO manner are inherently tied to resource acquisition. More fundamentally, one is inherently about data, and the other is inherently about control-flow... simply put, they're different tools with different use cases, even though people don't bother to make the distinction. Nevertheless, if people insist on using the same hammer for both nails, the language needs to address this fundamental issue before people can claim it's possible to do scope(exit) or the equivalent in C++.
- lomnakkus 9y agoI'm not sure I understand what you mean. For your "release resources" point: fclose() can fail, yet in fstream::~fstream() that must be ignored. So that's not great. For your "execute after prior operations in LIFO manner" point... what is the purpose except to clean up resources? If it isn't about scoped resources, then what is it about, given that defer(...) is explicitly about scope? I mean, if "defer" wasn't about that, we'd just write a few more statements doing the thing and not bother with the whole defer(...) thing?!?
- mehrdadn 9y ago> For your "release resources" point: fclose() can fail, yet in fstream::~fstream() that must be ignored. So that's not great. No, fclose() cannot fail to close the file. The return code merely tells you whether any pending write operations have failed in the meantime, which is unrelated to the releasing of the FILE. The FILE will be closed either way. The C standard is explicit about this: Whether or not the call succeeds, the stream is disassociated from the file and any buffer set by the setbuf or setvbuf function is disassociated from the stream (and deallocated if it was automatically allocated). http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1256.pdf#page=282 http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1256.pdf#pa... > For your "execute after prior operations in LIFO manner" point... what is the purpose except to clean up resources? Well, fflush() is an easy example. Or, any logging that must occur at the end of a function call regardless of its success or failure. Or, really, anything else that isn't releasing a resource...
- lomnakkus 9y agoHang on, isn't fclose() tasked with flushing buffered I/O, or are we assuming entirely synchronous I/O? Well, I suppose fsync() absolves POSIX of that, but in practice? fstream::~fstream() has to flush the IO (at least at runtime library level) and if that fails? > The FILE will be closed either way. That doesn't matter. It only matters in a resource-accounting way -- the resource will be freed, but that program does the wrong thing (partial write, 50-50 whether write happens, whatever). > > For your "execute after prior operations in LIFO manner" point... what is the purpose except to clean up resources? > Well, fflush() is an easy example. Or, logging that must occur at the end of a function call regardless of its success or failure. Or, really, anything else that isn't releasing a resource... fflush() can also fail (see above). Logging can also fail, disastrously, if it's going through a serial port -- though, it technically doesn't necessarily break the program's semantic meaning -- nobody wants to wait for N hours for the next log statement to be sent before continuing on with the program's execution. Do you see, now, what I mean? (EDIT: I think HN screwed up the quoting on my reply, but I think I've fixed it. Please yell if I quoted you or me(!) badly.)
- mehrdadn 9y ago> Hang on, isn't fclose() tasked with flushing buffered I/O You're not reading carefully. I never said fclose() flushes anything. Please go back and read what I wrote. >> The FILE will be closed either way. > That doesn't matter. It only matters in a resource-accounting way. The resource will be freed, but that program does the wrong thing (partial write, 50-50 whether write happens, whatever). fflush() can also fail. Logging can also fail, disastrously [...] Yes, you are only confirming what I wrote. Again, please go back and read what I wrote; it seems you are not reading carefully and are very confused what I have been saying (and what you yourself were asking). Here, I'll quote myself again. I said: "Destructors are meant to release resources, whereas finally/scope(exit) are meant to execute after prior operations in a LIFO manner." You were surprised these are distinct categories and wanted examples of the operations that would need to occur in a LIFO order but which are not releasing any resources. I cited flushing and logging as easy examples of such operations. You then proceeded to object that fflush and logging can... fail? Yes, I agree; of course they can -- indeed that was half of my entire point as to why they are inappropriate for destructors/RAII, but appropriate for finally/scope(exit). To repeat even more explicitly: both flushing and logging would need to occur in finally{} blocks, as they are not releasing any resources. In addition, neither of them is appropriate for a destructor, because these operations can fail, and destructors cannot propagate the corresponding exceptions. By contrast, closing a file needs to occur in a destructor, because is releasing a resource (which inherently cannot fail). And indeed, this implies fclose() would need to be called in a destructor and have its return value ignored, as it always succeeds in closing the file.
- vvanders 9y agoThis is my big gripe with exceptions and why I'm happy that Rust doesn't have them(yes I know there's panics but that's a separate thing). Every C++ project I've worked on has turned them off both for this and for the RTTI savings(less of an issue these days).
- dbaupp 9y agoTo be fair, Rust doesn't solve the errors-in-destructors thing any better: Drop::drop can't return anything.
- vvanders 9y agoIt's not that hard to work around that, you just pass a reference in on creation that gets filled on drop(). The exception case is much nastier and a lot less explicit.
- dbaupp 9y ago"Just" passing a reference elides how clunky and annoying it is: depending on the code, it requires extra nested scopes, along with remembering to actually handle the error. Even the case of propagating the error upwards requires a bunch of annoyance: let mut failed = Ok(()) { let object = create_it(..., &mut failed); // ... } // destructor runs failed?; C++11 introduces a pile of tools for first-class manipulation of exceptions as values (the <exception> header), that mean that even using exceptions, the handling in a destructor can be fairly similar to your suggestion for Rust (e.g. wrap the contents of the destructor in a try/catch, and then fill in an exception_ptr& using current_exception()). The main difference is type erasure and allocation in C++. In any case, in either language, an object storing a reference to fill in later restricts how the object can be used, since it can no longer escape from the stack frame which owns the data to which the reference points.
- vvanders 9y agoExcept every exception in C++ is unchecked. Literally every API call can throw the entire world at you and you won't know it until you run the code under each permutation. This includes library code that you may not have the source for. Compared to the above I at least know from an API signature that there's the possibility of an error.
- beached_whale 9y agoI don't think I understand, you can throw from a destructor. However, in C++11 it gets tricky because destructors are implicitly declared noexcept, so if you want to do so you need to mark them noexcept(false). As for implementing scope(exit) yeah, apparently this isn't possible.
- mehrdadn 9y ago> I don't think I understand, you can throw from a destructor Read what I wrote carefully: >> destructors invoked via exceptions can't throw their own exceptions i.e. if you are in a block where an exception is thrown, and a destructor is called during the exception's propagation, then that destructor cannot throw its own exception, as it will terminate the program. (This is unrelated to noexcept.) See here for more info: https://stackoverflow.com/a/130123 https://stackoverflow.com/a/130123
- beached_whale 9y agoAh I see, like struct B { ~B( ) noexcept( false ) { throw ...; } }; struct A { B b; ~A( ) noexcept( false ) { throw...;} }; I guess the saving grace is that most C++ devs are aware of what could throw in a destructor because it is rare and C++ 11 made this more difficult. Just don't and design around it. If the destructor fails use it as a choice to terminate or ignore.
- mehrdadn 9y agoYeah. But when people start writing wrappers like SCOPE_EXIT that call user code inside destructors, suddenly the users of those wrappers don't have any way to know they can't throw exceptions.
- beached_whale 9y agoscope_exit is just not very idiomatic C++. If used, It's for quick'n'dirty I'm too rushed to wrap it in a class times. It's use in C++ implies that you are worrying about something at the wrong abstraction level too. With that though, I would think that the default > c++11 implicit noexcept is proper. Crash hard when an exception is thrown and maybe even static assert on the result of noexcept( on_exit_cb ) so that it gives a compile error, lambda's can be noexcept and c functions cannot throw(thinking fclose and friends)
- deathanatos 9y ago> destructors invoked via exceptions can't throw their own exceptions `finally`, in languages that have it (and presumably, scope(exit) too), face fundamentally the same problem with exceptions that destructors do: if an exception is already propagating, and you throw another one, what happens?, since you (presumably) can't have two exceptions. C++ says tough / don't do that / you're terminated. Other languages just forget about the other exception, and you lose the context (which can be a pain to debug; though I think more recent versions of Python, for example, will attach the original exception as a "context" to the new one) but your program continues execution. Languages that expose a result object, e.g., Result in Rust, force you to deal with the issue yourself, essentially, by deciding at the site what to do with it. (The downside being the increased amount of code, though to some extent I believe the language can supply tooling to help there; Rust is again a good example. The upside is you get to choose what happens.) (I see these more as a tradeoff, that different languages have different opinions about.)
- deleted 9y ago[deleted]
- cjalmeida 9y agoJava from the beginning allows you to chain exceptions and that is a core part of debugging. In Python this is a very recent construct and few libraries use it, unfortunately.
- maxlybbert 9y agoThat’s funny, because I really dislike “finally,” because it isn’t much better than doing all the cleanup yourself. The design document for Java try-with-resources says that Sun’s own programmers working on the standard Java libraries got it wrong a third of the time. I find it interesting that C#, Java and Python have each created some kind of automatic cleanup mechanism even though they already had “finally.” That suggests to me that “finally” has some big drawbacks.
- mehrdadn 9y agoThe drawback is that the finally block is far away from the set-up block, which makes it painful to maintain and allows them to get out of sync pretty easily. It's a syntactic issue rather than a semantic issue. (This is only referring to use cases other than resource release.)
- maxlybbert 9y agoThat is probably the most well-known problem, but it’s not the only one. Another issue is that people generally don’t test failures as much as they should. They’ll generally get “everything must be rolled back” but mess up “only some things should be rolled back.”
- uep 9y agoAndrei Alexandrescu has a fun talk about implementing scope_exit using a new C++17 function: std::uncaught_exceptions (which is a tweak to std::uncaught_exception). Fundamentally, it doesn't really solve the destructor throwing exceptions issue though. https://www.youtube.com/watch?v=WjTrfoiB0MQ https://www.youtube.com/watch?v=WjTrfoiB0MQ