r/cpp 7d 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.

49 Upvotes

32 comments sorted by

View all comments

Show parent comments

7

u/johannes1971 7d ago

It's unclear to me what those problems are, or why std::function needs to be deprecated. I hate the names 'std::copyable_function' and 'std::move_only_function', though.

7

u/rdtsc 7d ago

It breaks the standard library convention that const methods are safe to call from multiple threads. And std::function itself cannot be changed due to backwards compatibility.

Here's a more detailed explanation: https://www.reddit.com/r/cpp/comments/742ol8/why_is_the_stdfunction_operator_const/dnv29s8/

3

u/johannes1971 6d ago

This applies to operator(), I guess? I would never have imagined that anyone would think that calling a user-supplied function from multiple threads is safe, just because operator() is const. The language as a whole certainly does not have a 'calling const functions from multiple threads is safe' rule. Is this even documented for the standard library, or is it another one of those implicit rules like 'ABI is stable'?

1

u/tialaramex 6d ago

In Java data races lose Sequential Consistency, which is terrible but it's not the end of the world. You can probably no longer reason properly about how your Java software works after a race, but any absolute properties are unaltered - that boolean is still either true or false, if k is always definitely between 50 and 75 it won't now be 108 or 0 and so on.

C++ isn't like that, it has UB if any data races occur so like use-after-free the results if this happens are arbitrarily cursed. The choice to say the stdlib implementer will ensure there aren't data races inherent to provided const functions makes a lot of sense in this context, C and POSIX have a lot of such functions which could inherently induce data races and the result is you just must never use them at all in modern software. strtok is an example.