June 13, 2026

Callbacks in Modern C++: Function Pointer, Lambda, Template, std::function, or Interface?

Callbacks are not only a syntax choice. They are an API contract about lifetime, ownership, performance and who controls the flow of execution.

In many C++ projects, callbacks slowly become messy because the first version is usually simple. A function pointer is added. Then a lambda is needed. Then the callback must be stored. Then someone captures this. Then the callback crosses a thread boundary. Suddenly a small design detail becomes a source of crashes, hidden allocations and unclear ownership.

Modern C++ gives us several ways to express callbacks: function pointers, lambdas, templates, std::function, and classic interfaces. None of them is the universal answer. The practical question is: what kind of callback contract do you want to expose?

Note

This article is not about making one callback style look modern and the others obsolete. It is about choosing the callback type that communicates intent clearly and does not surprise the caller.

The real question: what does the callback mean?


Before choosing a callback type, do not start with syntax. Start with the relationship between the caller and the callee.

  • Is the callback called immediately? A forwarding reference or template callable may be enough.
  • Is the callback stored for later? You need an owning wrapper or an object with a clear lifetime.
  • Does the callback need captures? A plain function pointer will not be enough.
  • Is this a hot path? Avoid unnecessary type erasure and hidden allocations.
  • Is this a stable public boundary? Runtime polymorphism may be more appropriate than exposing templates.
  • Are there several related operations? An interface may express the protocol better than several unrelated callbacks.

The callback type should make these answers visible. A callback is not just something you can call. It is part of your API design.

Start with the simplest option: no callback


Sometimes the best callback is no callback at all. A callback is useful when the caller wants to inject behavior, react to an event, customize an algorithm or handle asynchronous completion. If the function can simply return a value, prefer that.

bool isValid(const Packet& packet);

// Simpler than:
void validate(const Packet& packet, std::function<void(bool)> onResult);

The second version looks more flexible, but it also makes control flow less direct. The caller has to ask: when is the callback called? Is it called once? Can it be called from another thread? What happens if validation throws or fails?

Tip

Use a callback when the caller needs to customize behavior or react later. Do not use a callback only to avoid returning a value.

Function pointers: good for simple C-style hooks


A function pointer is the smallest and most restrictive callback form. It can point to a free function or a static member function. It cannot store captures.

using PacketCallback = void (*)(std::span<const std::byte> packet);

void forEachPacket(PacketReader& reader, PacketCallback callback)
{
    while (auto packet = reader.read()) {
        callback(*packet);
    }
}

void logPacket(std::span<const std::byte> packet)
{
    // write packet to log
}

forEachPacket(reader, &logPacket);

This is simple and predictable. There is no allocation, no type erasure object, and no question about captured state. That is also the limitation. The moment the caller needs local state, a function pointer becomes awkward. Function pointers are still useful when you need a C-compatible callback, a very small hook, or a callback that deliberately must not capture state.

Warning

Do not use a function pointer just because it looks cheap. If the caller needs state, you will probably reinvent state passing with void*, globals or static variables. That usually makes the API worse.

functionpointers

Lambdas: great at the call site


Lambdas are often the most readable way to provide small behavior at the call site. They keep the logic near the operation that uses it.

std::size_t accepted = 0;

forEachPacket(reader, [&](std::span<const std::byte> packet) {
    if (isValid(packet)) {
        ++accepted;
        send(packet);
    }
});

This is clear because the callback is local. You can see what it captures, what it does, and why it exists. Lambdas work especially well with algorithms, retry helpers, small filters, and short synchronous operations.

The danger starts when the lambda is stored or executed later. Captures that are safe during a synchronous call may become dangling references in asynchronous code.

class Worker
{
public:
    void start()
    {
        scheduler_.post([this] {
            doWork(); // dangerous if Worker is destroyed before the task runs
        });
    }

private:
    void doWork();
    Scheduler& scheduler_;
};

The code is compact, but the lifetime contract is hidden. The lambda stores a raw this pointer. If the scheduler runs the task after the object is destroyed, the callback becomes a use-after-free bug.

Warning

Capturing this in a callback that may outlive the current call is a lifetime decision, not just a convenience. Make the ownership model explicit.

class Worker : public std::enable_shared_from_this<Worker>
{
public:
    void start()
    {
        auto self = shared_from_this();
        scheduler_.post([self] {
            self->doWork();
        });
    }

private:
    void doWork();
    Scheduler& scheduler_;
};

This version keeps the object alive until the callback runs. That may be the right design, but it is a real ownership decision. In other systems you may prefer cancellation tokens, weak pointers, explicit stop methods, or a scheduler that guarantees callbacks are drained before destruction.

lambdacaptures

Template callables: zero-overhead customization


When a function only needs to call the callback during the current call, a template callable is often a very good fit. It accepts lambdas, function objects and function pointers without type erasure.

#include <functional>
#include <utility>

template <typename Callback>
void forEachPacket(PacketReader& reader, Callback&& callback)
{
    while (auto packet = reader.read()) {
        std::invoke(std::forward<Callback>(callback), *packet);
    }
}

This version is flexible and efficient. The compiler knows the exact callback type, so it can inline aggressively. It also works naturally with capturing lambdas.

std::size_t bytes = 0;

forEachPacket(reader, [&bytes](std::span<const std::byte> packet) {
    bytes += packet.size();
});

The cost is that the implementation usually lives in a header, error messages can become more complex, and every distinct callback type may instantiate a new version of the template. That is often fine for algorithms and hot paths, but not always ideal for stable module boundaries.

Tip

Use template callables for synchronous customization, generic algorithms and hot paths where avoiding type erasure matters. Avoid exposing templates when you want a stable ABI-like boundary or a small compile surface.

template <typename Callback>
requires std::invocable<Callback&, const Packet&>
void forEachPacket(PacketReader& reader, Callback&& callback)
{
    while (auto packet = reader.read()) {
        std::invoke(callback, *packet);
    }
}

With C++20 concepts, you can make template callback errors more readable. The important part is still the same: the callback is a compile-time customization point, not a runtime object stored for later.

std::function: a useful boundary, not a free abstraction


std::function is a type-erased owning callback wrapper. It is useful when you want to store a callback, replace it at runtime, pass it through non-template interfaces, or keep implementation details out of headers.

#include <functional>
#include <utility>

class EventDispatcher
{
public:
    using Handler = std::function<void(const Event&)>;

    void setHandler(Handler handler)
    {
        handler_ = std::move(handler);
    }

    void dispatch(const Event& event)
    {
        if (handler_) {
            handler_(event);
        }
    }

private:
    Handler handler_;
};

This is a clean runtime boundary. The dispatcher does not care whether the handler is a lambda, function object or function pointer. It owns a callable object and invokes it later.

Logger logger;
EventDispatcher dispatcher;

dispatcher.setHandler([&logger](const Event& event) {
    logger.write(event);
});;

dispatcher.dispatch(Event{.name = "connected"});

The trade-off is that std::function hides the concrete callable type. That can mean lost inlining, type-erasure overhead and sometimes allocation depending on the callable and implementation. In most control-plane code this may not matter. In a tight data path or embedded hot loop, it can matter.

Warning

std::function is not wrong. The mistake is using it blindly for every callback, including hot paths and simple synchronous customization points where a template callable would be clearer and cheaper.

Another important detail: std::function is copyable and traditionally requires its stored callable to be copy-constructible. If your callback owns a move-only resource, you may need a different design, such as a move-only wrapper, an interface, or C++23 std::move_only_function where available.

stdfunction

Interfaces: better when the callback becomes a protocol


A single callback is good for one event. But when you have several related events, a named interface can be clearer than passing several independent functions.

class IConnectionObserver
{
public:
    virtual ~IConnectionObserver() = default;

    virtual void onConnected() = 0;
    virtual void onDisconnected() = 0;
    virtual void onError(ConnectionError error) = 0;
};

class Connection
{
public:
    explicit Connection(IConnectionObserver& observer)
        : observer_(observer)
    {
    }

private:
    IConnectionObserver& observer_;
};

This expresses a relationship, not just a callback. The connection has an observer. The observer has a known set of operations. The lifetime is also more visible because the constructor takes a reference.

An interface is often a good fit when the callback target is a real object with responsibilities, state and several methods. It also works well with dependency injection and tests.

class FakeConnectionObserver : public IConnectionObserver
{
public:
    void onConnected() override
    {
        connected = true;
    }

    void onDisconnected() override
    {
        disconnected = true;
    }

    void onError(ConnectionError error) override
    {
        lastError = error;
    }

    bool connected{false};
    bool disconnected{false};
    std::optional<ConnectionError> lastError;
};

The downside is ceremony. An interface is heavier than a lambda when all you need is one small action. Virtual calls also add runtime dispatch. That is usually acceptable for event-style boundaries, but unnecessary for small local algorithms.

Tip

When the callback starts to look like a conversation between two objects, consider an interface. When it is only one small action, prefer a callable.

interfacevscallable

Borrowed callback or stored callback?


One of the most important API questions is whether the callback is borrowed only for the duration of the call or stored for later. The type should make this obvious.

A template callable often communicates: “I will call this now.”

template <typename Callback>
void retry(int attempts, Callback&& operation)
{
    for (int i = 0; i < attempts; ++i) {
        if (std::invoke(operation)) {
            return;
        }
    }
}

A setter that accepts std::function communicates: “I will keep this callback.”

void setCompletionHandler(std::function<void(Result)> handler)
{
    completionHandler_ = std::move(handler);
}

A reference to an interface communicates: “I refer to an existing object, and that object must outlive me or be detached safely.”

class Download
{
public:
    explicit Download(IDownloadObserver& observer)
        : observer_(observer)
    {
    }

private:
    IDownloadObserver& observer_;
};

Warning

The worst callback APIs are the ones where the caller cannot tell whether the callback is called immediately, stored, copied, moved, invoked on another thread, or invoked more than once. Document and encode that contract.

ownership&lifetime

Be explicit about how often the callback is called


A callback API should also communicate call count. Is it a one-shot completion callback? A repeated event handler? A filter? A visitor? These are different contracts.

// One-shot completion callback.
using CompletionHandler = std::function<void(Result)>;

// Repeated event callback.
using EventHandler = std::function<void(const Event&)>;

// Predicate used immediately by an algorithm.
template <typename Predicate>
std::vector<Packet> filterPackets(std::span<const Packet> packets,
                                  Predicate&& predicate);

The names help. CompletionHandler suggests one completion result. EventHandler suggests repeated calls. Predicate suggests a synchronous decision. The type alone does not always tell the full story, so naming matters.

Tip

Use names like CompletionHandler, Observer, Predicate, Visitor and Filter. They make callback intent easier to understand during code review.

Avoid std::bind in new code


std::bind is still part of C++, but lambdas are usually clearer in modern code.

auto callback = std::bind(&Device::setMode, &device, std::placeholders::_1);

The lambda version is easier to read, easier to debug, and makes captures explicit.

auto callback = [&device](Mode mode) {
    device.setMode(mode);
};

There are exceptions, but for most new C++ code, a lambda is the more readable way to adapt a function call.

A practical decision table


Here is a practical starting point for code reviews:

SituationPreferWhy
C API, no captures, simple hookfunction pointerSmall, explicit, compatible with C-style boundaries
Local behavior at the call sitelambdaReadable, captures local state intentionally
Synchronous generic algorithmtemplate callableNo type erasure, good inlining, flexible
Store one runtime callbackstd::functionOwns the callable and hides concrete type
Store move-only callbackmove-only wrapper / std::move_only_functionKeeps move-only ownership possible
Several related callback methodsinterfaceExpresses a protocol between objects
Hot embedded data pathtemplate or direct callAvoid hidden allocation and dispatch overhead
Public stable module boundarystd::function or interfaceAvoid exposing implementation templates unnecessarily

Common mistakes


A few callback mistakes show up often in real projects.

  • Using std::function everywhere. It is convenient, but not always the right cost model.
  • Using templates across every boundary. This can increase compile time and expose implementation details.
  • Capturing this in async callbacks without a lifetime plan. This is a common source of use-after-free bugs.
  • Passing several unrelated callbacks instead of naming a protocol. An interface may be clearer.
  • Using a function pointer when state is needed. That usually leads to awkward workarounds.
  • Not documenting the execution context. The caller should know whether the callback runs now, later, once, many times, or on another thread.
  • Ignoring cancellation. Stored callbacks often need a way to disconnect or prevent calls during shutdown.

A review checklist


When reviewing a callback API, I would ask these questions:

  1. Is the callback called immediately or stored?
  2. Can the callback be called more than once?
  3. Which thread invokes it?
  4. Can it be invoked after the owner starts destruction?
  5. Does it need to capture local state?
  6. Does it need to own move-only resources?
  7. Is the callback in a hot path?
  8. Would an interface communicate the relationship better?
  9. Is cancellation or unregistration needed?
  10. Does the call site clearly show ownership and lifetime?

Example: choosing between the options


Imagine a packet reader. For a small synchronous helper, a template callable is a good fit:

template <typename Callback>
void readAll(PacketReader& reader, Callback&& onPacket)
{
    while (auto packet = reader.read()) {
        std::invoke(onPacket, *packet);
    }
}

For a dispatcher that stores a handler and calls it later, std::function is clearer:

class PacketDispatcher
{
public:
    using Handler = std::function<void(const Packet&)>;

    void setHandler(Handler handler)
    {
        handler_ = std::move(handler);
    }

    void onPacketReceived(const Packet& packet)
    {
        if (handler_) {
            handler_(packet);
        }
    }

private:
    Handler handler_;
};

For a connection that has several related events, an interface is often more readable:

class IPacketSessionObserver
{
public:
    virtual ~IPacketSessionObserver() = default;

    virtual void onSessionStarted() = 0;
    virtual void onPacket(const Packet& packet) = 0;
    virtual void onSessionClosed() = 0;
};

The goal is not to force one style. The goal is to choose the one that tells the truth about the relationship.

callbackdecision

Embedded C++ angle


In embedded and system-level C++, callback design matters because the hidden costs are not only theoretical. A callback may run in a timing-sensitive path. It may be called from an event loop. It may cross a thread boundary. It may hold references to objects that are being shut down.

That does not mean you should avoid std::function. It means you should put it in the right place. A control API, configuration layer or UI event boundary may be perfectly fine with std::function. A packet processing loop, audio path or low-latency scheduler might prefer a template callable, direct interface, or a design that avoids callbacks in the hot path.

Rule of thumb

Use the most explicit callback type that fits the boundary. Prefer templates for synchronous zero-overhead customization, std::function for stored runtime callbacks, and interfaces when the callback becomes a long-lived protocol.

The key idea


If you remember only one thing, remember this:

Tip

A callback type should describe the contract: called now or later, owning or non-owning, single action or protocol, cheap hot path or stable runtime boundary.

Function pointers, lambdas, templates, std::function and interfaces are all useful. Problems start when we choose one by habit instead of intent.

Good modern C++ APIs make the callback relationship visible. They do not only compile. They tell the caller who owns the callback, when it runs, what it may capture, and how long everything must stay alive.