skip to content

In C++, what can a std::function<int(int)> hold, and what happens when you call one that is empty?

level: juniorimportance: must knowfreq 70%

answer

  1. any copyable callable, one signature
  2. functions, functors, capturing lambdas
  3. copying copies the target
  4. empty call throws

basics

~10 s

std::function<int(int)> holds any copy-constructible callable that can be called with an int and returns something convertible to int: a function, a function object or a capturing lambda. Calling an empty one throws std::bad_function_call.

solid answer

~40 s

`std::function<R(Args...)>` is a **type-erasing wrapper**: one type that can hold any callable whose call with `Args...` yields something convertible to `R`. A `std::function<int(int)>` can hold a pointer to `int square(int)`, a function object with a matching `operator()`, or a lambda with captures, and you can reassign it to a different kind of callable later. The held object, the **target**, must be copy-constructible, because copying a `std::function` copies its target. A default-constructed `std::function`, or one assigned `nullptr`, is **empty**: it converts to `false`, and calling it throws `std::bad_function_call`. Conversions apply at the boundary, so a target returning `short` from a `long` parameter still fits `int(int)`.

code

cpp · 26 lines
cpp
#include <cstdio>
#include <functional>

int square(int x) { return x * x; }
struct AddN {
  int n;
  int operator()(int x) const { return x + n; }
};

int main() {
  int offset = 100;
  std::function<int(int)> f = square;                          // free function
  std::printf("%d ", f(3));
  f = AddN{5};                                                  // function object
  std::printf("%d ", f(3));
  f = [offset](int x) { return x + offset; };                   // capturing lambda
  std::printf("%d\n", f(3));

  std::function<int(int)> none;                                 // empty
  std::printf("empty? %s\n", none ? "no" : "yes");
  try {
    none(1);
  } catch (const std::bad_function_call&) {
    std::printf("calling it threw std::bad_function_call\n");
  }
}

go deeper

for a junior

Know that std::function stores any callable with a matching signature, including capturing lambdas, and that calling an empty one throws std::bad_function_call.

for a middle

Explain the rules: callable with conversions, copy-constructible target, copying copies the target, and the explicit operator bool for emptiness.

for a senior

Recognise the costs behind the convenience, an indirect call and possible allocation, and the const operator() that still mutates a mutable target.

for a principal

Decide where type erasure belongs in an API and where a template parameter or a non-owning reference would serve callers better.

## One type for many callables Every lambda has its own unnamed type and every function object class is a different type, so a variable, a data member or a container cannot hold "any callback" unless something hides those types. `std::function<R(Args...)>`, declared in `<functional>`, is the standard library's answer: a **polymorphic function wrapper** that stores, copies and calls any callable object matching a **call signature**. The template argument is a function type. `std::function<int(int)>` means: callable with one `int`, producing a result usable as an `int`. ## What a std::function<int(int)> can hold | Target | Example | Accepted because | |---|---|---| | pointer to function | `square`, declared `int square(int)` | it is callable with `int` and returns `int` | | function object | `AddN{5}` with `int operator()(int) const` | its call operator matches | | lambda with captures | `[offset](int x) { return x + offset; }` | a closure is a function object | | function object with convertible types | `short operator()(long) const` | the `int` argument converts to `long`, the `short` result to `int` | | empty | default-constructed, or assigned `nullptr` | holds nothing | Two rules decide what is accepted: - **Callability**: the target, called as an lvalue with the arguments, must yield something implicitly convertible to `R`. That is why a function object taking `long` and returning `short` fits `int(int)`. - **Copyability**: the target type must be **copy-constructible**. A lambda whose init capture holds a `std::unique_ptr` is move-only, so constructing a `std::function` from it fails to compile. With libc++, Clang reports `call to implicitly-deleted copy constructor` of the lambda. A pointer to member function is callable too, if the object is passed as the first argument: a `std::function<void(Scheduler&, int)>` can hold `&Scheduler::run`. ## Copying, assigning and emptiness 1. **Copying** a `std::function` copies its target. A stateful function object therefore gets an independent copy; the two wrappers no longer share state. 2. **Moving** transfers the target and leaves the source in a valid but unspecified state, so do not rely on it being empty afterwards. 3. **Assigning** a new callable replaces the target, whatever its previous type was. The code example reassigns one variable from a function to a function object to a lambda. 4. **Testing**: `if (f)` uses the explicit `operator bool`, which is `false` for an empty wrapper; `f == nullptr` says the same. 5. **Calling an empty wrapper** throws `std::bad_function_call`, which derives from `std::exception`. The example catches it. ## Declaring and inspecting a wrapper Since C++17, class template argument deduction can supply the signature: ```cpp std::function f = square; // std::function<int(int)> std::function g = [](double d) { return d * 2; }; // std::function<double(double)> ``` Deduction works for function pointers and for function objects with a single, non-overloaded call operator; the standard notes that the deduced types might change in future revisions, so spelling the signature is still the safer habit in headers. Two members expose the target: `target_type()` returns the `std::type_info` of the stored type (`typeid(void)` when empty), and `target<T>()` returns a pointer to the target if its type is exactly `T`, otherwise a null pointer. ## The call itself `std::function::operator()` is declared `const` and forwards the arguments to the target. The wrapper's own type does not reveal the target's type, so the call goes through an indirection chosen at construction time. That makes it flexible but not free: the call usually cannot be inlined, and storing a large target may allocate memory. Those costs are the subject of the scheduler profiling question. ## Mistakes interviewers listen for - Believing `std::function` holds only plain functions, or only captureless lambdas. - Believing calling an empty `std::function` is a no-op, or undefined behaviour. It throws `std::bad_function_call`. (For C++23's `std::move_only_function`, calling an empty wrapper *is* undefined behaviour: its call operator has a precondition instead.) - Believing copies share one target through reference counting. - Expecting a move-only lambda to fit. It does not; the target must be copy-constructible. - Confusing the wrapper with the lambda's own type: `auto` keeps the exact closure type, `std::function` erases it. ## How to answer Say it holds any copy-constructible callable matching the signature, with conversions on arguments and result, that copying copies the target, and that an empty wrapper is `false` and throws `std::bad_function_call` when called. Mention that erasing the type has a cost.

  • How does std::function's operator() being const interact with a mutable lambda target?
    `std::function::operator()` is `const`, yet it calls the target as a non-const lvalue, so a `mutable` lambda inside a `const std::function` still changes its own state: a counter stored that way returned 1, then 2. The wrapper's `const` does not protect the target. C++23's `std::move_only_function` and C++26's `std::copyable_function` encode const-ness in their signatures to close that gap.
  • Can a std::function<void(Job&)> hold a pointer to the member function void Job::run()?
    Yes. `std::function` calls its target through the standard's INVOKE rules, so for a pointer to member function the first argument is used as the object: `std::function<void(Job&)> f = &Job::run; f(job);` calls `job.run()`. The same applies to a pointer to data member, which acts as a getter.

  • std::function can hold only plain functions or captureless lambdas.
  • Calling an empty std::function does nothing and returns.
  • Copies of a std::function share one target through a reference count.
  • Any lambda fits in a std::function, including one owning a std::unique_ptr.
  • The target's signature must match the wrapper's signature exactly.