|
|
Nicolas Alvarez wrote:
> All this is from Wikipedia article "C++0x". Next time please do some minimal
> research before claiming C++ sucks :)
Oh, I see the answer to my question.
"""
Closure variables for local variables can also be defined without the
reference symbol &, which indicates that the lambda function will copy the
value. This forces the user to declare their intent to reference local
variables or copy them. If a closure object containing references to local
variables is invoked after the innermost block scope of its creation, the
behaviour is undefined.
"""
So, basically, you don't really have lambda expressions. You have something
that looks like a lambda expression but is really a pointer to a chunk of
code. An actual lambda expression closes over variables, not over values.
And it's a value itself, not a chunk of code that isn't possible to evaluate
outside the context in which it was created.
You can't do something like
std::vector<std::function> xyz() {
struct { int a; } alpha;
std::vector<std::function> stuff;
for (int i = 0; i < 10; i++) {
stuff.pushback([](int x) { return alpha.a += x + i; };
}
return stuff;
}
void main() {
std::vector<std::function> thing1 = xyz();
std::vector<std::function> thing2 = xyz();
...
}
Basically, if you actually use a closure (rather than a downward funarg),
you wind up with undefined behavior. I'm sorry to say, that means C++'s
lambdas suck, and technically aren't even lambda expressions.
(Note this works fine in languages like C#, for example, because you
actually can have pointers that get cleaned up when you're done, so you can
generate code that allocates struct alpha on the stack and keeps it until
you throw away all the lambda expressions.)
> All this is from Wikipedia article "C++0x". Next time please do some minimal
> research before claiming C++ sucks :)
Oh, C++ sucks for a lot more reasons than just next decade's changes. ;-)
--
Darren New, San Diego CA, USA (PST)
My fortune cookie said, "You will soon be
unable to read this, even at arm's length."
Post a reply to this message
|
|