Le 2023-11-30 19:20, Andrey Semashev via Boost a écrit :
On 11/30/23 17:54, Julien Blanc via Boost wrote:
I can add support for default construcion, if that is considered useful by the community.
I think it does not hurt for scope_fail and scope_exit. We have scope_final for the simple case. I'm asking because i finally added it to the scope_exit-like we use in our code base. But we also have a type erased self-contained function object, which solves the issue below.
The example with std::function is not really the best practice, as the section follows on after that example. You should generally avoid it, as it may throw on construction/assignment and therefore break your exception safety.
Indeed. I fear, however, that people will just come up with this code,
use it without understanding the implications. I think Andrzej made a
very good point
(https://lists.boost.org/Archives/boost//2022/05/253109.php) by saying
that examples should be exempts from anti-patterns / bad code. I try to
keep that in mind now when doing a review.
To get back on the default construction, after more thoughts on this, it
looks like a good rationale (can't guarantee that assignment will be
nothrow) for *not* providing default construction. But doesn't that
apply more generally? Isn't writing code like that:
std::function
There is a guarantee that scope guard construction won't throw, unless constructing one of the function objects throws. This implies that the scope guard itself doesn't do anything that may throw, which includes dynamic memory allocation.
Thanks, this is the kind of definitive answer i was looking for. I could unfortunately not find it in the documentation, though. I think it deserves to be added (if it is present, then it probably should be emphasized more).
unique_resource is not designed to handle IO errors, it simply ensures you don't leak the resource. The actual correctness of resource management is still user's responsibility.
...
Again, unique_resource is not about error handling, or IO in general for that matter. Its only purpose is to free the resource on destruction.
However, I can update the example the way you suggest, to avoid the confusion.
I think there's indeed a dangerous confusion here, and it is exacerbated by the fact that both reside in the same library / namespace. scope_exit / scope_fail are helpers to write correct code. unique_fd is just about not leaking resources. That is indeed definitely not the same thing. Anyone who cares about file integrity won't use it when writing files (i have yet to see an raii design that works for file integrity). Regards, Julien