Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Differences between std::function_ref and delegates

What are the differences between the new std::function_ref, that was added to C++26, and a "delegate"? Are they the same?

By "delegate" I mean:

  • A type that has sizeof(...) == 16.
  • It can store a pointer to a class and a pointer to a class member function. Invoking the delegate then invokes the pointed-to class member function on the pointed-to class.
  • It can also store plain functions.
  • It's described in the following articles:
  • Member Function Pointers and the Fastest Possible C++ Delegates
  • The Impossibly Fast C++ Delegates
  • The Impossibly Fast C++ Delegates, Fixed
like image 714
Toby Brull Avatar asked Jul 25 '26 02:07

Toby Brull


1 Answers

std::function_ref and this "delegate" are conceptually the same thing, a pointer to a "thunk" and a pointer to an object on which the function is called on, but std::function_ref allows you to constrain the const/volatile/noexcept type of the called function.

  • std::function_ref<void()> can point to any callable.
  • std::function_ref<void() const noexcept> can only point to a callable with a const noexcept call operator (or member function), or noexcept free functions.

constraining a function to be const is useful in multithreaded code to document that it will be called concurrently by multiple threads. (it doesn't replace proper documentation, but it will reduce mistakes)

constraining functions to be noexcept is useful to document that it will be called in a context that cannot propagate or catch exceptions, such as being called from other languages, or across C library boundaries.

like image 110
Ahmed AEK Avatar answered Jul 27 '26 17:07

Ahmed AEK



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!