Skip to content
Tutorials Center
My learning

Topics

Lesson 53 of 171 ยท Functions

Callbacks: Function Pointers, std::function and Lambdas

Design callbacks in C++: compare function pointers, templates and std::function, pass state safely, unsubscribe with RAII handles, handle exceptions and use move_only_function.

A callback is a piece of code that you hand to someone else so they can run it later. The "someone else" might be a sort routine asking how to compare two items, a download that reports progress, a button that tells you when it was clicked, or a worker thread announcing that it has finished. You write the what; the other code decides the when.

The mechanics of the three main tools are covered elsewhere: Function Pointers and std::function, Lambdas and Function Objects. This lesson is about the design questions you face when you build or use a callback API. Which parameter type should it take? How does a callback get its data? How long may the library keep it? What if it throws, or unsubscribes itself, or runs on another thread? Getting those right is what separates a callback API that is pleasant from one that crashes in production.

Three ways to accept a callback

An API that takes a callback has three realistic parameter types, and each makes a different trade.

  1. A function pointer, void (*)(int). Tiny and compatible with C libraries, but it can only hold plain functions and captureless lambdas.
  2. A template parameter, template <typename F> void run(F callback). Accepts anything callable, and the compiler can inline the call, so it costs nothing. The callback's type is part of the function's type, so you can't store different callbacks in one variable.
  3. std::function<void(int)>. One concrete type that can hold any callable with that signature, including lambdas that capture state. It costs an indirect call and possibly a heap allocation.

The same progress-reporting function written all three ways shows how little the caller's code changes:

C++ One caller, three callback parameter types

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

The function pointer accepts print_percent and a captureless lambda but would reject the lambda that captures seen, because a capturing lambda needs somewhere to keep its captured variables and a bare pointer has no room for them. The template and std::function versions accept both.

A practical rule: use a template parameter when the callback is only called during the function (sorting, for_each-style loops, one-shot actions). Use std::function when the callback is stored in a member or a container, outlives the call, or crosses a library boundary where you don't want templates. Use a function pointer for C APIs. C++23 adds a fourth option, std::move_only_function, covered near the end.

Giving a callback its data

A callback usually needs context: which window was clicked, which request this reply belongs to. C++ lambdas make that easy by capturing variables, but you'll also meet the older C convention, where the API takes a function pointer plus a void* it hands back untouched.

C++ The C-style void* context, wrapped safely

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

The C-style call works, but nothing checks that &summary really is a Summary*: pass the wrong pointer and static_cast silently reinterprets memory. The wrapper keeps the same C interface but stores the lambda's address in the void* and casts it back in a captureless "trampoline" lambda, so callers write ordinary capturing lambdas and never see a cast. This is how C++ code talks to C libraries such as qsort_r, pthread_create and GUI toolkits. If you design a new API in C++, skip the void* and accept a template parameter or std::function instead.

Lifetimes: how long can the library keep your callback?

Calling a callback during a function is safe: everything it captured is still alive. Storing a callback for later is where most callback bugs come from. A lambda that captures this or a local variable by reference becomes a time bomb if the object or scope goes away before the callback fires (see the dangling captures section in Lambdas).

Three habits keep stored callbacks safe.

  • Capture by value (or by shared_ptr) for callbacks that outlive the current scope. Never capture locals by reference in a callback you store.
  • Let the subscriber unsubscribe. Whoever registers a callback must be able to remove it before the objects it uses are destroyed.
  • Make unsubscribing automatic. Return an RAII object from subscribe whose destructor removes the callback, so forgetting is impossible.

The event source below follows all three. It also handles two situations that trip up simple implementations: a callback that unsubscribes itself while the source is iterating over callbacks, and a callback that throws.

C++ An event source with RAII subscriptions

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Handlers run in subscription order, the throwing handler is reported but doesn't stop the others, and temporary disappears from the list the moment its Subscription leaves scope. Note the [[nodiscard]] on subscribe: if a caller ignores the returned handle it is destroyed immediately, and the handler would be unsubscribed at once, which is a bug the compiler can now warn about. Also notice emit iterates over a copy of the handlers. Without the copy, a handler that calls erase on the map while the loop is iterating over it would invalidate the iterator, which is undefined behavior. Real signal libraries solve this the same way or defer removals until dispatch ends. See Design Patterns for a weak_ptr-based alternative.

Exceptions, return values and early exit

A callback is code you don't control running inside code you wrote. Decide up front what happens when it misbehaves.

  • Let it propagate if the callback's failure should abort the whole operation (as with std::for_each and the algorithms). Make sure your function is exception-safe, so it leaves no half-finished state behind (see Exception Safety).
  • Catch and report if one bad listener must not stop the others, as above. Catching ... hides bugs, so at least log what you caught.
  • Declare noexcept when the callback cannot be allowed to throw, for example from a destructor or from a C library that calls back through C frames. An exception escaping a noexcept function calls std::terminate. Never let an exception unwind through C code; the behavior is undefined.

Callbacks can also steer the caller through their return value. A common design is a visitor that returns bool: true to continue, false to stop early. That is cleaner than throwing an exception to escape a loop.

C++
template <typename F>
void for_each_until(const std::vector<int>& values, F&& visit) {
    for (int value : values) {
        if (!visit(value)) {
            return;                      // callback asked us to stop
        }
    }
}

for_each_until(numbers, [](int n) {
    std::println("{}", n);
    return n < 15;                       // stop once we pass 15
});

Finally, be careful about reentrancy: a callback may call back into the object that invoked it. A button handler that disables the button, or a listener that subscribes a new listener, are ordinary things to do. The snapshot in emit above is what makes them safe. When you write a class that calls callbacks, finish updating your own state before you call them, so a callback that re-enters sees a consistent object.

Move-only callbacks and callbacks on other threads

std::function requires its callable to be copyable, which rules out lambdas that capture a std::unique_ptr or a std::promise. C++23 adds std::move_only_function, which holds any callable, including move-only ones, and is never copied. It's the right type for one-shot tasks and completion handlers.

Completion callbacks are often invoked from a different thread than the one that registered them. That has two consequences. The callback must synchronize any shared data it touches (see Mutexes and Locks), and you must keep everything it uses alive until it has run.

C++ A completion callback on a worker thread

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

The handler owns a unique_ptr through its capture, which std::function would refuse to store but std::move_only_function accepts. It runs on the worker thread, which the output confirms, and the latch lets main wait until it has finished before printing the last line. The worker is a std::jthread, so its destructor joins the thread and the program never exits while the handler is running. For callbacks that need results instead of side effects, futures are often a better fit than callbacks; see Async and Futures.

Choosing a style

Need Use
Callback is called during the function, nothing is stored Template parameter
Stored callback, copyable std::function<Sig>
Stored or one-shot callback with move-only captures std::move_only_function<Sig> (C++23)
C API, or no state needed Function pointer (or a captureless lambda)
Unsubscribe needed Return an RAII Subscription

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which callback parameter type can accept a lambda that captures local variables?

    A capturing lambda has state, so it cannot convert to a plain function pointer. Template parameters and std::function can hold it.
  2. 2. You store a lambda that captures a local variable by reference and call it after the function has returned. What happens?

    Capturing by reference does not extend lifetime. Stored callbacks should capture by value or by shared_ptr.
  3. 3. Why does the EventSource example iterate over a copy of its handlers in emit?

    Callbacks can re-enter the object that called them. Iterating a snapshot (and re-checking membership) makes unsubscribing during dispatch safe.
  4. 4. Which type should hold a one-shot completion handler that captures a std::unique_ptr?

    std::function requires copyable callables. std::move_only_function (C++23) accepts move-only ones such as lambdas that capture a unique_ptr.
  5. 5. What is the main benefit of returning an RAII Subscription object from subscribe()?

    Tying unsubscription to a destructor means a subscriber that goes away can never be called again, with nothing to remember.

Summary

  • A callback is behavior passed to other code. Accept it as a template parameter when it is only used during the call, as std::function when it is stored, as std::move_only_function for move-only one-shot callbacks, and as a function pointer for C APIs.
  • Capturing lambdas carry state; C-style APIs pass state through a void*, which you can hide behind a small template trampoline.
  • Stored callbacks must not capture locals by reference. Capture by value, and give subscribers an RAII handle that unsubscribes automatically.
  • Decide what happens when a callback throws (propagate, catch per listener, or noexcept), and never let exceptions unwind through C code.
  • Callbacks may re-enter your object or run on another thread: update your state before calling them, iterate a snapshot, and synchronize shared data.

Next: References, where you'll learn how C++ lets one variable become another name for an existing object.