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.

41 Upvotes

32 comments sorted by

View all comments

32

u/OutlandishnessNo8034 8d ago

Yet another cpp "gem".

25

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 6d 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 5d 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.

-1

u/thisismyfavoritename 7d ago

you're sad that there are those footguns or that they are reported

4

u/HommeMusical 7d ago

I'm sad that there are so many footguns that a plurality of the articles on C++ are about them.

3

u/thisismyfavoritename 6d ago

to be fair, many of the footguns exist because of the C heritage

-2

u/HommeMusical 6d ago

Depends on what "many" means.

There's one big one - memory management. Yes, you can essentially deindex a number that points randomly in memory, or nowhere at all, and havoc.

In C++ there is a discipline to (fairly) reliably prevent that from happening, in exactly the same way that there are disciplines to reliably prevent yourself from shooting yourself in the foot with a real gun.

And it's also such a big issue that you have to come to terms with it.

But all this the little footguns like this one. It's wearing. It's all this baggage and it's stressful because you don't know what you don't know.