Re: Lambda allocations
On Jan 2, 8:05 am, rgba32 wrote:
Lambdas are a new-ish topic for me. As I dive in an learn more about
them, it occurred to me that there may be some "hidden" memory
allocations happening to account for the cases where a closure and
it's state need to outlive the scope it was created in.
No. Wrong mindset. The compiler won't do anything magical w.r.t.
allocation. Lambda expressions are just syntactical sugar for
something we already are familiar with: function objects. There is no
inherent heap allocation or ref-counting going on. If you see
something like this in the assemblies then this is entirely due to the
involvement of user-defined classes with ctors and dtors doing some
memory management.
Example:
int main()
{
vector<int> iv = int_vec_source();
// xor metric sorting
int key = 42;
string msg = "hello!";
sort(iv.begin(), iv.end(),
[&,key](int l, int r){
cout << msg << endl;
return (l^key) < (r^key);
});
return 0;
}
would be equivalent to
struct some_unique_lambda_class
{
public:
some_unique_lambda_class(int key_, string& msg_)
: key(key_), msg(msg_)
{}
void operator()(int l, int r) const
{
cout << msg << endl;
return (l^key) < (r^key);
}
private:
int key; // "capture by copy"
string& msg; // "capture by reference"
};
int main()
{
vector<int> iv = int_vec_source();
// xor metric sorting
int key = 42;
string msg = "hello!";
sort(iv.begin(), iv.end(),
some_unique_lambda_class(key,msg));
return 0;
}
Cheers!
SG
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]