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

Standard Library Function Helpers

A comprehensive overview of function helpers in the standard library, including std::invocable, std::predicate and std::function.

Questions & Answers

Answers are generated by AI models and may not have been reviewed. Be mindful when running any code on your device.

Performance Considerations with std::function
Are there any performance considerations I should be aware of when using std::function?
Storing Member Functions in std::function
Can I store a member function in a std::function object? If so, how do I invoke it?
Using the Predicate Concept with Member Types
Can I use the std::predicate concept with member functions that take member types as arguments?
Invoking Multiple std::function Objects
How can I store and invoke multiple std::function objects?
Using Lambdas with std::function
Can I use lambda expressions with std::function? Are there any limitations?
Or Ask your Own Question
Get an immediate answer to your specific question using our AI assistant