Re: lambda objects not assignable
On Friday, November 16, 2012 1:20:11 AM UTC-8, MJanes wrote:
{ Please avoid double-spacing the quoted material.
This article has been reformatted manually by the moderator. -mod }
{ The same applies to this article as well.
Please respect the mod comment when you quote one! :) -mod }
On Tuesday, November 13, 2012 8:51:22 PM UTC+1, Gene Bushuyev wrote:
Maybe I'm missing something here, but apart from self-assignment
there isn't any other object of the same closure type, so what would
be the use of copy assignment?
it's common for generic code to accept functors by value ( including
the STL ); therefore, non-copy-assignable lambdas would be nearly
useless ...
I don't see why that should be true. Lambdas are copyable/moveable,
and can be used with any standard library function/class, which copies
or moves its objects. They are definitely not useless.
I worked on AXE library (parser generator, using many C++11 facilities),
which depends on copying or moving lambdas, but I can't think of a use
case, which would require lambda assignment.
I guess the standardization committee didn't come with useful cases of
the assignment either.
On Thursday, November 15, 2012 2:17:25 AM UTC+1, Zhihao Yuan wrote:
I think this is the main reason -- lambda types are identical to each
other, and both the lambda and their type are unnamed. Assignment does
not work with different types. And self-assignment is impossible,
because lambda is a prvalue.
the fact that lambdas and their types are unnamed it's not relevant,
beacuse you can always write template code deducing the lambda type
and instantiating it however you like. Moreover, lambdas can have
state so they are not always identical to each other; for example,
consider
int i1 = 0;
auto f1 = [=](int v) mutable -> int { int l = i1; i1 = v; return l; };
auto f2 = f1;
f1(1);
f2(2);
// now f1,f2 have different states; with assignability, you could put
these things, say, in an STL vector
I don't see how it would be useful putting lambdas in std::vector.
I also wouldn't want anybody writing code like the above copying and
modifying lambda state as it will be either unnecessary complication
or a hack. Having said that, it's not difficult to simulate lambda
assignment:
template<class T>
T& assign(T& t1, const T& t2)
{
void* ptr = &t1;
t1.~T();
return *new(ptr) T(t2);
}
see full test: http://ideone.com/GyEkHd
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]