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 call
To 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 empty
By 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.
Answers to questions are automatically generated and may not have been reviewed.
A comprehensive overview of function helpers in the standard library, including std::invocable
, std::predicate
and std::function
.