First, std::function
is required to avoid allocation in the case where the target is a function pointer of std::reference_wrapper
; implementations are encouraged to avoid allocation for "small" targets:
[...] for example, where f
's target is an object holding only a pointer or reference to an object and a member function pointer.
That means that copying a std::function
whose target is large will involve an allocation and a copy of the target (reference counting is not permitted, since the target might have mutable state). However, in your specific case the copy will be elided since you are calling your function with a prvalue temporary.
In your specific case, since you are calling the function immediately you don't need to worry about taking ownership of it, so it would be better to take the function by const reference. Taking it by rvalue reference would cause a headache to a user who has an existing lvalue or const reference to a function; they would need to std::move
it (in the former case) or create a prvalue temporary copy (in the latter case).