5

I'm watching Herb Sutter's CppCon 2014 talk about lock-free programming.

On handout page 7, we have the following code:

static unique_ptr<widget> widget::instance;
static std::once_flag widget::create;

widget& widget::get_instance() {
    std::call_once( create, [=]{ instance = make_unique<widget>(); } );
    return *instance;
}

My question: Why is a [=] capture used here, rather than [&] (or maybe just []?)

cppreference says:

[=] captures all automatic variables used in the body of the lambda by copy and current object by reference if exists

but we don't have any automatic variables nor do we need the current object.

Wolfie
  • 27,562
  • 7
  • 28
  • 55
einpoklum
  • 118,144
  • 57
  • 340
  • 684
  • 8
    I'd even ask "rather than `[]`". Looks odd indeed. – Quentin Feb 05 '18 at 12:35
  • 2
    Of course, this is also obviously-not-real-code. The `return` on the next line won't compile anyway. – T.C. Feb 05 '18 at 12:38
  • I think that's a mistake, it also needs to `return *instance;` – Yola Feb 05 '18 at 12:39
  • I was under the impression that you really only want `[=]` when the lambda might outlive any of the variables captured with `[&]`, right? – hegel5000 Feb 05 '18 at 13:21
  • 1
    @hegel5000: Not necessarily. You could "cannibalize" your equals-captured locals just like you can do with copy-by-value parameters to functions (e.g. advance an iterator many times). – einpoklum Feb 05 '18 at 13:24
  • @Yola: That's Sutter's code, not mine... but I'll change it. – einpoklum Feb 05 '18 at 13:27
  • 4
    The point I was trying to make is that this is a completely untested snippet that was written solely to illustrate one particular thing (the use of `call_once`), and so there's not much point trying to read too much into the fine details. – T.C. Feb 05 '18 at 13:29
  • @T.C.: Make that an answer? – einpoklum Feb 05 '18 at 14:13

1 Answers1

1

There's no need for a capture-default here. [] would do just fine.

As I wrote in the comments, this is an untested snippet written to illustrate a completely unrelated thing (i.e. call_once). There's not much point trying to read too much into it.

That said, as far as the genre of "untested snippet written to fit on a slide" is concerned, [=] is probably the safest default lambda-introducer: [&] might cause data races or dangling references, [] would be wrong if you ever need to capture, and explicit captures take up valuable space on the slide - and require actually thinking about captures......

T.C.
  • 133,968
  • 17
  • 288
  • 421