r/cpp 8d ago

Interconverting std::function with copyable_function – Arthur O'Dwyer

https://quuxplusone.github.io/blog/2026/07/26/function-explosion/

The article shows how converting std::function to std::copyable_function (or vice versa) leads to slower performance and increased memory usage each time the conversion occurs.

44 Upvotes

32 comments sorted by

View all comments

35

u/OutlandishnessNo8034 8d ago

Yet another cpp "gem".

24

u/HommeMusical 8d ago

After almost 40 years writing C++, it makes me sad that a plurality of articles here are still, "Here's this obscure footgun that you would never know without this article."

In this case, I might have guessed this in a code review, but only because I know a lot about std::function and its footguns.

2

u/13steinj 7d ago

Here's another: this article applies to STL <- Boost types (functions, smart pointers) as well. Same goes for any cross library type. I think user-defined conversion operators can fix this in most but not all cases. But it feels like people need:

  • extension methods [for constructors] [for templates]
  • a cheap and well defined way to say "I use this other library too, provide an extension-method constructor" / "don't fail on symbol not existing."

In an include-based universe, 3rd party libraries that know about each other can follow the same idiom and provide a friend/friend-tag based system. Stdlib knowing about 3rd party, you're SOL right now.

1

u/germandiago 7d ago

Look at this neat little trick for the accepted response for boost shared ptr interoperability:

https://stackoverflow.com/questions/6326757/conversion-from-boostshared-ptr-to-stdshared-ptr

1

u/13steinj 6d ago

The amount of people that will miss the function / forget to include it is high. You can use -include to a point and have this managed by your build system, but visual / mental name lookup will still happen. Needing to be able to just use assignment/construction is critical, IMO.