C++11 introduced std::function as a type-erased callable-object holder. function was badly designed in a few ways: Its rarely used “go fish” API bloats every user; it advertises operator() const even when the controlled object’s operator() is mutating; it handles what should be a precondition violation by throwing an exception, which again bloats every user and means its operator() can never be noexcept. So C++26 fixed these problems by adding std::copyable_function . (Which preserves some of function ’s suboptimal design decisions: copyable_function<bool()> remains implicitly convertible to copyable_function<void()> , contextually convertible to bool , and assignable from nullptr .)
P2548 “ copyable_function ” (Hava 2023) contains this guidance for implementors:
It is recommended that implementors do not perform additional allocations when converting from a copyable_function instantiation to a compatible move_only_function instantiation, but this is left as quality-of-implementation.
Note that converting in the other direction — from move_only_function to copyable_function — is disallowed: copyable_function can hold only copyable callables, and move_only_function is not copyable.
But copyable_function is interconvertible — both directions — with std::function ! Both of these type-erased wrappers are constructible from anything that is copyable and callable, and themselves are copyable and callable. So we can do this:
std::function<int()> f = []{ return 5; }; std::copyable_function<int() const> cf = std::move(f); std::function<int()> g = std::move(cf);
You’d hope the move from f into cf would be implemented something like this:
and vice versa for the move back into g :
But if copyable_function doesn’t know about function , it might just treat f the same as any old rvalue of copyable, callable type: it might move a copy of f onto the heap to own.
And vice versa for the move back into g : function might just treat cf the same as any old rvalue of copyable, callable type, and move a copy of cf onto the heap to own.
... continue reading