Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > C++ > Lambda function capturing and memory usage

Reply
Thread Tools

Lambda function capturing and memory usage

 
 
Juha Nieminen
Guest
Posts: n/a
 
      04-22-2012
I was wondering: Does memory usage increase every time that a lambda
function captures variables, especially if it's then stored into a
std::function wrapper?

This question came up when I was thinking about a rather functional
example usage of lambdas, like this:

std::function<int(int)> multiplierFunction(int multiplier)
{
return [](int value) { return value * multiplier; };
}

The above function could be used eg. like:

auto doubler = multiplierFunction(2);
auto tripler = multiplierFunction(3);
auto nMultiplier = multiplierFunction(n);

std::cout << doubler(5) << " " << tripler(x) << " "
<< nMultiplier(y) << "\n";

The values '2', '3' and 'n' have to be stored somewhere for (at least)
as long as 'doubler', 'tripler' and 'nMultiplier' exist. Where are they
stored and for how long? (Are they freed immediately when those variables
go out of scope? How?)

What worries me is the possible memory usage if the above function is
used eg. in a loop, like:

for(int i = 0; i < 1000000; ++i)
{
auto f = multiplierFunction(i);
std::cout << f(2) << "\n";
}

Does memory usage increase a million-fold, or is the memory recycled after
each loop?
 
Reply With Quote
 
 
 
 
Juha Nieminen
Guest
Posts: n/a
 
      04-22-2012
Juha Nieminen <(E-Mail Removed)> wrote:
> std::function<int(int)> multiplierFunction(int multiplier)
> {
> return [](int value) { return value * multiplier; };
> }


Of course I meant:

return [multiplier](int value) { return value * multiplier; };
 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
Type of lambda function returning a lambda function... Haochen Xie C++ 4 03-17-2013 11:23 PM
Lambda function capturing and memory usage Juha Nieminen C++ 6 04-24-2012 04:26 PM
C++0x lambda and capturing computed values Sohail Somani C++ 5 05-07-2009 07:58 PM
lambda vs non-lambda proc Steve Dogers Ruby 1 03-30-2009 10:11 PM
Re: Lambda as declarative idiom (was RE: what is lambda used for inreal code?) Roman Suzi Python 13 01-07-2005 09:33 PM



Advertisments