Re: Lambda allocations
Thanks for the replies.
SG, your example fails to take into account the part of my mail when I
ask what happens when a closure needs to outlive the scope it was
created in. I realize that a lambda is just syntactic sugar for a
functor, but we'd still have these allocation issues with a functor,
which, in the past, we'd be left to handle
manually ourselves.
To illustrate my point, consider the following example:
#include <functional>
void *operator new(size_t size)
{
void *p = malloc(size);
printf("operator new : 0x%08x %d\n", p, size);
return p;
};
void operator delete(void *p)
{
printf("operator delete : 0x%08x\n", p);
free(p);
};
// all simple types
struct MyData
{
int a;
float b;
char c[16];
};
std::function<void()> GetLambda(MyData const &data)
{
// capture data by value
return ([data]()
{
printf("data = %d, %f, %s\n", data.a, data.b, data.c);
});
}
int main()
{
std::function<void()> lambda;
{
// data scope is limited to this block
MyData data;
data.a = 10;
data.b = 20.f;
strcpy_s(data.c, "hello world");
lambda = GetLambda(data);
}
lambda();
return 0;
}
The output of this program is:
operator new : 0x002c3c40 28
data = 10, 20.000000, hello world
operator delete : 0x002c3c40
which shows there are indeed some non-obvious (hidden is perhaps the
wrong term) allocations going on to extend the scope of MyData to
where it's used.
Dave, are these the allocations you refer to when you say:
"If your capture list always looks like [] or [&] I think no
reasonable
implementation will generate an allocation. If your capture list uses
[=] or lists the names of locals without using &, then dynamic
allocations should occur only as required by the copy constructors of
the local variables."
I'm unclear since none of the class members themselves require dynamic
memory allocations in their copy ctors.
Mark
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]