C++ Logo

sg14

Advanced search

Interesting idea for non-throwing std::function

From: Patrice Roy <patricer_at_[hidden]>
Date: Mon, 3 Oct 2022 17:23:01 -0400
Hi everyone!

In another thread, I mentioned the fact that many people in SG14 have
stated that they would not use std::function since it might allocate.
Jonathan Wakely (followed by a few others) suggested an interesting
approach that I don't think we discussed previously:

What about making the constructor conditionally noexcept? The
> implementation knows whether a given type will be stored on the heap, and
> if that type can be constructed without throwing, so can easily expose that.
>
> What people care about is a property of the constructor, so why not make
> it part of the constructor signature?
>
> You can static assert is_nothrow_constructible.
>

If the SG14 contributors like this, we could turn it into a paper. It would
(IMO) have a good chance of being accepted. This would let people use
std::function without any risk of allocating in the cases where they care
about this, and at essentially no cost. And if someone thinks all
std::function cases in their codebase should be protected that way, they
could envision writing a make_function() factory that would do this at no
cost either, being essentially

template <class F> std::function<F> make_function(F && f) {
   static_assert(std::is_nothrow_constructible_v<std::function<F>>);
   return { std::forward<F>(f) };
}

What do you think?

Cheers!

Received on 2022-10-03 21:23:13