Let's say I have a function which takes an std::function
:
void callFunction(std::function<void()> x)
{
x();
}
Should I pass x
by const-reference instead?:
void callFunction(const std::function<void()>& x)
{
x();
}
Does the answer to this question change depending on what the function does with it? For example, if it is a member function or constructor which stores or initializes the std::function
into a data member.
If you're worried about performance, and you aren't defining a virtual member function, then you most likely should not be using
std::function
at all.Making the functor type a template parameter permits greater optimization than
std::function
, including inlining the functor logic. The effect of these optimizations is likely to greatly outweigh the copy-vs-indirection concerns about how to passstd::function
.Faster: