Standard Library Function Helpers

Calling an Empty std::function

What happens if I try to call a std::function object that is empty?

Abstract art representing computer programming

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 computer programmer
Part of the course:

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Free, unlimited access

This course includes:

  • 124 Lessons
  • 550+ Code Samples
  • 96% Positive Reviews
  • Regularly Updated
  • Help and FAQ
Free, Unlimited Access

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Screenshot from Warhammer: Total War
Screenshot from Tomb Raider
Screenshot from Jedi: Fallen Order
Contact|Privacy Policy|Terms of Use
Copyright © 2024 - All Rights Reserved