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.
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......
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With