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&
?
1 Answer
Functors can have state that they modify. If you make the functor const
then it can't modify that state.
-
how about predicates to standard algorithms? Unless otherwise specified, algorithms that take function objects as arguments can copy those function objects freely, 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?) Jan 28, 2021 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
tostd::generate
to create a range of random values. Jan 28, 2021 at 22:13
const&
should also work, but is less performant?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.std::function
. If you pass a function by having a templated function, it fits more to this question: stackoverflow.com/questions/65562986/…