Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exception safety of std::function

I tried without success to find if this code could throw an exception :

std::function<void(void)>f=[]{};

According to the standard, the copy or move constructor of std::function are not noexcept. But I guess the lack of the noexcept keyword is due to the fact that std::function also wrap user defined functor object whose copy or move constructors could throw.

In my case an exception seems very unlikely but is it possible at all ?

like image 857
Arnaud Avatar asked May 21 '13 08:05

Arnaud


1 Answers

In my case an exception seems very unlikely but is it possible at all ?

In principle, yes. std::function will have to allocate memory to store the callable object it's initialised with, and if that memory is allocated dynamically then there's the possibility of failure.

In practice, in your case, no. In the words of a note in the specification, "Implementations are encouraged to avoid the use of dynamically allocated memory for small callable objects". A lambda with no captures is convertible to a function pointer, which is about as small as a callable object gets; so a good implementation should certainly store that without dynamic allocation. And of course, copying a pointer can't throw either.

Larger objects (including lambdas with many captures) will need dynamic allocation, and need to copy their captured objects or other state, and so can't offer a no-throw guarantee.

like image 136
Mike Seymour Avatar answered Oct 31 '22 21:10

Mike Seymour