Re: lambda : capturing a data member - is it legal?
Am 18.02.2011 13:51, schrieb Helmut Jarausch:
Hi,
reading Scott Meyers' "Overview of the New C++" I stumbled over
#include<algorithm>
#include<list>
class Widget {
public:
void doSomething();
private:
std::list<int> li;
int minVal;
};
void Widget::doSomething() {
auto it = std::find_if(li.cbegin(), li.cend(),
[minVal](int i) { return i> minVal; } // error?
);
}
Scott says, that the second to last line is in error and 'repairs' it by
capturing 'this' instead of minVal.
On the other hand, gcc-4.5.2 accepts the code above.
GCC is here non-conforming versus the current wording, see
5.1.2 [expr.prim.lambda] p. 10:
"The identifiers in a capture-list are looked up using the usual rules
for unqualified name lookup (3.4.1); each such lookup shall find a
variable with automatic storage duration declared in the reaching scope
of the local lambda expression."
In your example, minVal is not a variable with automatic storage
duration, thus should not be captured.
If the code is is illegal, indeed, what's the rational behind it?
At the place of the definition of the lambda, the value of minVal is
available and it should thus be possible to capture it by value?
The question remains whether a user really understands what the meanings
are of implicit captures as in:
void Widget::doSomething() {
auto it = std::find_if(li.cbegin(), li.cend(),
[=](int i) { return i> minVal; } // ??
);
}
The current overly strictness could be relaxed in the future, but one
must take care that the relaxed rules are not worse than the current
ones ;-)
HTH & Greetings from Bremen,
Daniel Kr??gler
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]