1

I am fairly new to lambdas and I've come across a question...

What is the difference between those:
[&](const std::vector<int> &v)
[](const std::vector<int> &v, std::vector<Chrono *> &m_chronoSets;)
I need to access and modify m_chronoSets (it is reachable by capturing the whole context with [&]

In term of time (I guess the first one could be slower, taken that we send the whole context by reference?) and optimisation.

Thank you.

2
  • They are not equivalent. They take different number of arguments. To compare in "term of time and optimization" something has to be run and take time - please create a sample test case. Don't you want [&m_chronoSets](const std::vector<int> &v)? Commented Jan 27, 2020 at 18:20
  • KamilCuk's form is best if you capture, You should only capture what you are going to use. But as far as performance goes, the compiler is only going to code what is needed. Commented Jan 27, 2020 at 18:23

1 Answer 1

4

In [&](const std::vector<int> &v){...}, any outside value the lambda accesses other than v gets captured by reference inside the lambda itself. The caller of the lambda does not need to know or care anything about those values, it only has to pass in a vector<int> for the v argument.

In [](const std::vector<int> &v, std::vector<Chrono *> &m_chronoSets){...}, nothing is captured inside the lambda itself, so the caller of the lambda has to explicitly pass in a vector<int> for the v argument AND pass in a std::vector<Chrono *> for the m_chronoSets argument.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.