C++ Logo


Advanced search

Re: scope guard

From: Jens Maurer <Jens.Maurer_at_[hidden]>
Date: Wed, 4 Aug 2021 15:29:53 +0200
On 03/08/2021 15.18, Andrey Semashev via Std-Proposals wrote:
> On 8/3/21 4:02 PM, language.lawyer--- via Std-Proposals wrote:
>> On 03/08/2021 15:22, Andrey Semashev via Std-Proposals wrote:
>>> On 8/3/21 3:08 PM, Jens Maurer via Std-Proposals wrote:
>>>> On 03/08/2021 11.46, Baruch Burstein via Std-Proposals wrote:
>>>>> Hi.
>>>>> Why is there no generic scope guard in the standard library?
>>>>> I am sure there must have been such a proposal before, probably with
>>>>> an explanation of why it was not accepted, but I couldn't find it.
>>>> Try std::unique_ptr with a custom deleter.
>>> This only works for pointers.
>> unique_ptr can be used with non-pointers
>> https://stackoverflow.com/questions/15756960/using-unique-ptr-to-control-a-file-descriptor
>> https://stackoverflow.com/questions/24611215/one-liner-for-raii-on-non-pointer
> Ok, it is possible use it with non-pointers. Doesn't mean that's
> something you would normally do instead of just writing a dedicated
> handle class instead of struggling with unique_ptr.
> And scope guards are not just about RAII. Really, the point of a scope
> guard is to execute a piece of code. And to achieve that goal the
> language could offer a more appropriate syntax. Compare the amount of
> code you have to write to employ unique_ptr with something like this:
> scope_exit [&]
> {
> do_stuff();
> };
> where scope_exit would be a keyword. I'm not proposing this particular
> syntax, it's just an illustration.

In the interest of clarity, the shortest generic scope guard using
std::unique_ptr that I've come up with so far is:

template<class X>
using scope_guard = std::unique_ptr<void, X>;

void f()
  scope_guard guard(0, [](void*) { std::cout << "hi"; });


(class template argument deduction does the rest).


Received on 2021-08-04 08:29:59