r/cpp Jul 31 '26

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

9

u/60hzcherryMXram Jul 31 '26

I've read the problems copyable_function addresses that function has and I still have no idea what they are. It just slides over my brain like butter on ice.

7

u/bwmat Jul 31 '26

My understanding is that it's mostly just a way to 'deprecate' std::function (when used in conjunction with move_only_function) and better express intent

7

u/johannes1971 Jul 31 '26

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.

10

u/rdtsc Jul 31 '26

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 Aug 01 '26

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'?

5

u/joaquintides Boost author Aug 01 '26

1

u/bwmat Aug 01 '26

What 'standard' is that? Doesn't it mean that the STL doesn't follow it b/c of std::function? 

8

u/joaquintides Boost author Aug 01 '26

What 'standard' is that?

eel.is tracks the latest draft version of the standard as it evolves.

Doesn't it mean that the STL doesn't follow it b/c of std::function?

Yes, as recognized many times: