Double lock control - capture in lambda passed to call_once

I watch Herb Sutter CppCon 2014 talk about non-blocking programming.

In the handout of 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 is: why is [=] capture used and not [&] (or maybe just [] ?)

cppreference says:

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

but we do not have any automatic variables and do not need the current object.

+5
source share
1 answer

There is no need for a default hold. [] will be fine.

As I wrote in the comments, this is an unverified snippet written to illustrate a completely unrelated thing (i.e. call_once ). There is not much point in reading too much.

However, since the genre of "unverified fragment written for installation on a slide", [=] is probably the safest default lambda introducer: [&] can cause data races or dangling links, [] it would be wrong if you sometime capture is needed, and explicit captures take up valuable space on the slide - and require actually thinking about captures ......

0
source

Source: https://habr.com/ru/post/1275172/


All Articles