0

I am curious why std::lower_bound() asks for passing by value for the compare function rather than by reference?

Passing by value means a copy is needed, slowing things down; especially, if someone passes in a "big" compare function object.

4
  • It's often a good candidate for a move. Lambdas, temporary functor objects, function pointers. Commented Jun 20, 2013 at 2:14
  • Right, probably calling move constructor in the copy constructor? But I think move exists in C11 recently but this STL algo exists for a long time. Temporary function object can probably be identified and then optimized by the compiler, but seems like a constructor call per invocation will still happen. Passing a function pointer is still not as optimal as passing a function object by reference because it can't be possibly inlined. That's why I raised this question :( Commented Jun 20, 2013 at 2:36
  • The move constructor is separate from the copy constructor. I'm not sure about functors, though they could have figured they would probably have zero data members in C++03 or something. I really don't see passing a function pointer as a problem. Commented Jun 20, 2013 at 2:40
  • A function pointer requires deference and so the compiler can't do static binding (of course, you can argue that a good compiler might be able to do so but I doubt it is required by the standard). Commented Jun 20, 2013 at 2:49

1 Answer 1

4

Many if not most comparison objects are stateless and take almost no size (they can't have zero size though). Passing a reference could actually be more expensive than passing a stateless predicate by value (especially if the compiler is able to totally elide the copy).

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

1 Comment

This is actually an interesting answer. I will try to benchmark a bit. Thanks!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.