Defer macro for calling functors on scope exit

55 views
Skip to first unread message

Sergey Abbakumov

unread,
Sep 28, 2017, 1:12:45 PM9/28/17
to Chromium-dev
Hi,

Sometimes creating RAII-objects for resources is too tedious. This is a proposal for declarative scope exit functionality of a DEFER-like macro: https://chromium-review.googlesource.com/c/chromium/src/+/680814

What do you think of that?

Regards,
Sergey

Ryan Hamilton

unread,
Sep 28, 2017, 1:20:53 PM9/28/17
to sabba...@yandex-team.ru, Chromium-dev
Can you explain what you mean by tedious in this context? It's usual a simple matter of initializing a variable of some RAII type. Perhaps you have a example in mind?

--
--
Chromium Developers mailing list: chromi...@chromium.org
View archives, change email options, or unsubscribe:
http://groups.google.com/a/chromium.org/group/chromium-dev
---
You received this message because you are subscribed to the Google Groups "Chromium-dev" group.
To view this discussion on the web visit https://groups.google.com/a/chromium.org/d/msgid/chromium-dev/51a7b1ba-c3b5-4add-a40e-363cbd263003%40chromium.org.

Jeremy Roman

unread,
Sep 28, 2017, 1:31:42 PM9/28/17
to Ryan Hamilton, sabba...@yandex-team.ru, Chromium-dev
I'm kinda neutral about this, but it's worth noting that base::ScopedClosureRunner exists.

I also mildly prefer avoiding macro magic, and just doing something like:

auto close_on_exit = base::Defer([]() {
  // ...
});

if we really want to. (can use WARN_UNUSED_RETURN to avoid the obvious pitfall)

But it's not that bad as macros go.

Ken Rockot

unread,
Sep 28, 2017, 1:31:49 PM9/28/17
to Ryan Hamilton, sabba...@yandex-team.ru, Chromium-dev
The example given on the CL (closing an opened file) is itself dubious, as quite often there's at least one code path which persists the lifetime beyond function scope by passing the file handle to a new owner -- a situation DEFER doesn't address. Besides that, we already have movable scopers (e.g. base::File) for that case. It would be hard to argue that those existing types are more tedious to use than DEFER+lambdas.

Could you point to some other practical scenarios where existing code is or would be tedious to write without this macro?

Daniel Cheng

unread,
Sep 28, 2017, 3:13:25 PM9/28/17
to roc...@chromium.org, Ryan Hamilton, sabba...@yandex-team.ru, Chromium-dev
I'd be interested in some examples where this would be useful. It seems like in most cases, it's better to have an RAII type, since the logic to release the resource propagates with type, rather than requiring DEFER() be specified in multiple places.

Daniel

Reply all
Reply to author
Forward
0 new messages