Calling an Empty std::function
What happens if I try to call a std::function object that is empty?
If you attempt to call a std::function object that is empty, it will throw a std::bad_function_call exception. This exception is derived from std::exception and is defined in the <functional> header.
For example:
#include <functional>
#include <iostream>
int main() {
std::function<void()> Callable;
try {
Callable();
} catch (const std::bad_function_call& e) {
std::cout << "Caught exception: " << e.what();
}
}Caught exception: bad function callTo avoid this exception, you should always check if a std::function is empty before calling it. You can do this by using the operator bool() of std::function, which returns false if the std::function is empty, and true otherwise.
#include <functional>
#include <iostream>
int main() {
std::function<void()> Callable;
if (Callable) {
Callable();
} else {
std::cout << "Callable is empty";
}
}Callable is emptyBy checking the state of the std::function before calling it, you can avoid the std::bad_function_call exception and handle the case where the std::function is empty in a way that's appropriate for your program's logic.
Standard Library Function Helpers
A comprehensive overview of function helpers in the standard library, including std::invocable, std::predicate and std::function.