Std :: function exception security

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

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

According to the standard, the constructor for copying or moving the std :: function is no exception. But I think the lack of the noexcept keyword is due to the fact that std :: function also wraps a specific functor object whose copy or move constructors can throw.

In my case, an exception seems very unlikely, but is it even possible?

+4
source share
1 answer

In my case, an exception seems very unlikely, but is it even possible?

I guess, yes. std::function will have to allocate memory to store the called object with which it is initialized, and if this memory is allocated dynamically, then there is the possibility of failure.

In practice, in your case, no. According to the note in the specification, "implementations are advised to avoid using dynamically allocated memory for small called objects." A lambda without captures is converted to a function pointer, which is about as small as the called object; therefore, a good implementation should certainly maintain this without dynamic allocation. And of course, copying the pointer also cannot be selected.

Larger objects (including lambda with a large number of captures) need dynamic distribution and must copy their captured objects or other condition and therefore can not offer a guarantee without a throw.

+6
source

Source: https://habr.com/ru/post/1481893/


All Articles