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.
source share