cpp_weekly icon indicating copy to clipboard operation
cpp_weekly copied to clipboard

C++23's `move_only_function`

Open lefticus opened this issue 3 years ago • 1 comments

lefticus avatar Jun 23 '22 00:06 lefticus

Is there a difference with https://github.com/lefticus/cpp_weekly/issues/85?

fcolecumberri avatar Aug 01 '22 18:08 fcolecumberri

Coming soon. Here are the examples: https://compiler-explorer.com/z/bhv8Gq3G4

lefticus avatar Oct 08 '22 18:10 lefticus

Coming in Ep349, November 7, 2023

lefticus avatar Oct 18 '22 22:10 lefticus

https://youtu.be/OJtGOJI0JEw

lefticus avatar Nov 10 '22 21:11 lefticus

I think using the ASM output is not a correct representation of the advantages of move_only_function. What you observe as "less" code is simply that:

  • std::shared is a lot more heavy weight than unique_ptr.
  • the gnu move_only_function implementation uses a larger internal storage for the SBO which elide an allocation.

The gnu std::mofunc implementation will require a call for each move operation whereas the gnu std::function implementation will never need one as it only store trivially copiable types in SBO and if heap alloc there is, it will just do a pointer swap.

So in practice I would expect the move operation on an std::function storing your std::shared_ptr lambda example (the one which lead to a "shocking amount of code") to be faster than a std::mofunc move operation where the mofunc stores a unique ptr. Though I obviously did not test that so it is only speculations ;).

TLDR; I think that the only real advantage is if your type is only move constructible. I think you are still better of using std::function most of the time, even if your type is movable.

etiennemlb avatar Jan 08 '23 11:01 etiennemlb