I am trying to understand how functions (mainly lambda expressions) as function parameters exactly work. So why are for example comparison functions in the standard library passed by value and not by const&
?
Asked
Active
Viewed 57 times
0

Henk
- 826
- 3
- 14
-
In particular, the accepted answer provides an excellent explanation of a rather obscure reason of why function objects should be passed by value. – Sergey Kalinichenko Jan 28 '21 at 20:55
-
Does this also apply for functions with acutal arguments? And do I understand correctly that ```const&``` should also work, but is less performant? – Henk Jan 28 '21 at 21:00
-
Yes and yes: the same reasoning applies regardless of the number of arguments the function object takes, and your understanding about `const&` is correct. While you are at that page, consider looking at Ben Voigt's concise answer, it's a nice option to keep in mind. – Sergey Kalinichenko Jan 28 '21 at 21:05
-
The marked answer only talks about `std::function`. If you pass a function by having a templated function, it fits more to this question: https://stackoverflow.com/questions/65562986/c-best-practice-pass-use-only-not-stored-lambda-argument-to-function-by-con/65563714#65563714 – n314159 Jan 29 '21 at 16:27
1 Answers
1
Functors can have state that they modify. If you make the functor const
then it can't modify that state.

NathanOliver
- 171,901
- 28
- 288
- 402
-
how about predicates to standard algorithms? [Unless otherwise specified, algorithms that take function objects as arguments can copy those function objects freely](http://eel.is/c++draft/algorithms.requirements#10.sentence-1), hence a predicate that relies on modfiying internal state yields unpredicable results. Why make a copy in the first place? (or is my "hence" a false premise?) – 463035818_is_not_an_ai Jan 28 '21 at 22:09
-
1@largest_prime_is_463035818 It very well may give unpredictable results. That said, you still want to pass by value since otherwise you wouldn't be able to pass a `std::mt19937` to `std::generate` to create a range of random values. – NathanOliver Jan 28 '21 at 22:13