Should I copy an std::function or can I always take a reference to it?

Can I store the function as a reference since std::function is just a function-pointer and the ‘executable code’ of the function is guaranteed to stay in memory?

std::function is very much not just a function pointer. It’s a wrapper around an arbitrary callable object, and manages the memory used to store that object. As with any other type, it’s safe to store a reference only if you have some other way to guarantee that the referred object is still valid whenever that reference is used.

Unless you have a good reason for storing a reference, and a way to guarantee that it remains valid, store it by value.

Passing by const reference to the constructor is safe, and probably more efficient than passing a value. Passing by non-const reference is a bad idea, since it prevents you from passing a temporary, so the user can’t directly pass a lambda, the result of bind, or any other callable object except std::function<int(int)> itself.

Leave a Comment