Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a difference between [&foo]{ ... } capture and [foo]{ ... } capture if 'foo' is a reference variable?

Tags:

c++

c++11

lambda

For foo declared as Foo& foo = ...;, is there any difference between capture-by-value and capture-by-reference semantics for lambdas?

like image 592
Eloff Avatar asked Aug 31 '12 13:08

Eloff


People also ask

Are there any or is there a difference?

Which One Should You Use: Is There A or Is There Any? We must use 'a' with singular countable nouns and 'any' with uncountable nouns. We use 'is' with both singular countable nouns and uncountable nouns.

What's the difference between the two there?

Their is the possessive pronoun, as in "their car is red"; there is used as an adjective, "he is always there for me," a noun, "get away from there," and, chiefly, an adverb, "stop right there"; they're is a contraction of "they are," as in "they're getting married."

Which is grammatically correct different to or different from?

Regional Differences The one big difference between these terms is that 'different from' and 'different to' are standard in British English. 'Different than', meanwhile, is primarily used in American English. Generally, then, you will want to avoid 'different than' when writing for a British audience.

What does it mean by difference between?

The difference between two things is the way in which they are unlike each other.


2 Answers

I think you have fallen to a common misconception... references are aliases to real objects. After initialization, any use of the reference is exactly equivalent to an use of the original object. If you consider this, the question makes little sense. If the reference is the object, then the behavior of [foo](){} will be exactly the same regardless of whether foo is an object or a reference to the object.

like image 161
David Rodríguez - dribeas Avatar answered Oct 13 '22 00:10

David Rodríguez - dribeas


Yes, there is a difference.

§5.1.2 [expr.prim.lambda] p14

An entity is captured by copy if it is implicitly captured and the capture-default is = or if it is explicitly captured with a capture that does not include an &. For each entity captured by copy, an unnamed nonstatic data member is declared in the closure type. The declaration order of these members is unspecified. The type of such a data member is the type of the corresponding captured entity if the entity is not a reference to an object, or the referenced type otherwise.

So, if you capture an identifier that names a reference by value, you get a copy of the referenced object.

like image 23
Xeo Avatar answered Oct 12 '22 23:10

Xeo