Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Double-check lock pattern - capture in lambda passed to call_once

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.

like image 310
einpoklum Avatar asked Nov 18 '22 21:11

einpoklum


1 Answers

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......

like image 79
T.C. Avatar answered Dec 22 '22 23:12

T.C.