Lambda function capturing and memory usage

J

Juha Nieminen

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?
 
J

Juha Nieminen

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

Of course I meant:

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

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,537
Members
45,021
Latest member
AkilahJaim

Latest Threads

Top