Sitemap
Ng Song Guan

Ng Song Guan

Software engineer writing about computer systems. https://www.linkedin.com/in/song-guan-ng/

Diving into std::function

12 min readAug 13, 2025

--

In languages like Python and Rust, functions are first-class citizens: you can store them in variables, pass them around, and return them from other functions just like any other object. While C++ lacks native support for first-class functions, since C++11, the standard library has provided a close alternative: std::function.

std::function is a polymorphic function wrapper. It can hold any callable — lambdas, function pointers, or objects with operator() — as long as it matches the specified function signature. Once wrapped, the callable can be copied, moved, stored, and invoked.

In this article, I’ll look at when to use std::function, when to avoid it, and how such a magical abstraction works under the hood in a strongly-typed language like C++.

std::function 101

Let’s start with a few examples showcasing its flexibility:

#include <functional>
#include <string>
#include <cassert>

int add(int x, int y) {
return x + y;
}

struct AddT {
int operator()(int x, int y) {
return x + y;
}
};


int main () {
// Store function pointer
std::function<int(int, int)> func1 = add;

// Store lambda
std::function<int(int, int)> func2 = [](int x, int y) {
return x + y;
};

// Store a callable object
AddT add_obj;
std::function<int(int, int)> func3 = add_obj;

// Invoke the std::function
assert(func1(1, 2) == func2(1, 2));
assert(func2(1, 2) == func3(1, 2));


// Store lambda with captured variable
int z = 0;
std::function<int(int, int)> func4 = [z](int x, int y) {
return x + y + z;
};
}

Although these callables are of different types, they all share the same interface:

int(int, int) // Take in two int parameters and return an int.

Curiously, we are able to store all of them into the same type: std::function<int(int, int)>. std::function erases their concrete type and exposes only this signature. This process is called type erasure. It allows you to treat completely different callable types in the same way.

For example, using std::function, we can store different callables together in a single container and invoke them.

std::vector<std::function<int(int, int)>> store;
store.push_back(func1);
store.push_back(func2);
store.push_back(func3);
for (auto& f : store) {
std::cout << f(1, 2) << std::endl;
}

When to use std::function?

By providing a uniform interface for different callables, std::function enables runtime polymorphism in a more expressive way. Here are two common examples where std::function shines.

Producer-consumer task queue

Unlike inheritance-based polymorphism, std::function works without requiring us to create class hierarchies.

Consider a producer-consumer setup where a producer is generating tasks for a consumer to execute. Traditionally, you might do this with a base class and virtual functions:

// Base class for runtime polymorphism
struct Task {
virtual ~Task() = default;
virtual void execute() = 0;
};
// Derived class example
struct DoAbc : Task {
void execute() override {
std::cout << "abc" << std::endl;
}
};

// Another derived class example
struct DoXyz : Task {
void execute() override {
std::cout << "xyz" << std::endl;
}
};

// Create more derived classes as needed

// threadsafe queue that will be used by producer/consumer
threadsafe_queue<std::unique_ptr<Task>> queue;


// Producer thread pushes tasks
queue.push(std::make_unique<DoAbc>());
queue.push(std::make_unique<DoXyz>());

// Consumer thread executes tasks
auto task = queue.pop();
task->execute();

This works, but every new task type requires a new derived class, adding boilerplate and mental overhead.

With std::function, the same design is reduced to:

// threadsafe queue that will be used by producer/consumer
threadsafe_queue<std::function<void()>> queue;

// Producer thread pushes tasks
queue.push([](){ std::cout << "abc" << std::endl; });
queue.push([](){ std::cout << "xyz" << std::endl; });

// Consumer thread executes tasks
auto task = queue.pop();
task(); // Just call it

This version is:

  • More concise — no extra class declarations.
  • More expressive — the task’s logic is visible at the call site.
  • More flexible — the lambdas can be easily adjusted and capture state if needed.

Event-driven code

Another example is event-driven code where you register callbacks and trigger them when events occur. std::function allows us to store the callbacks in a single container.

Consider this event dispatcher, which invokes a registered callback when a file descriptor (fd) becomes ready:

class EventDispatcher {
private:
std::vector<std::function<void()>> callbacks;

public:
EventDispatcher(int max_fd) : callbacks(max_fd) {}

// Register a callback for fd
void register_callback(int fd, std::function<void()> cb) {
callbacks[fd] = std::move(cb);
}

// Handle event by calling registered callback for fd
void handle_event(int fd) const {
callbacks[fd]();
}
};


void regular_function() {
std::cout << "Callback from regular function" << std::endl;
}


int main() {
EventDispatcher dispatcher(10);

// Register the callbacks
dispatcher.register_callback(5, regular_function);

dispatcher.register_callback(6, [] {
std::cout << "Callback from lambda" << std::endl;
});

// Assume some code calls the following
dispatcher.handle_event(5);
dispatcher.handle_event(6);
}

Here, the callbacks come from both a normal function and a lambda, but the dispatcher is able to treat them uniformly thanks to std::function.

When not to use std::function?

std::function is powerful, but it is not a zero-cost abstraction. It adds runtime overhead in both performance and memory usage. Here are some cases where it is unnecessary.

Only passing a callable as a parameter

If you only need to accept a callable, invoke it immediately, and don’t need to store it, std::function is overkill.

Consider these two implementations of a run_task function:

#include <iostream>
#include <functional>

// Template-based
template <typename F>
void run_task1(F&& f) {
f();
}

// std::function-based
void run_task2(std::function<void()> f) {
f();
}

int main() {
run_task1([]() {
std::cout << "Running task (templated)" << std::endl;
});

run_task2([]() {
std::cout << "Running task (std::function)" << std::endl;
});
}

run_task1 is a function template that passes the lambda by its exact type. The compiler knows this type at compile time and the exact call destination so there’s no extra runtime cost here.

run_task2 wraps the lambda in a std::function<void()>, adding an extra layer of indirection and some runtime overhead¹ which we will discuss more later.

No runtime polymorphism needed

Even if you need to store a callable, if the callable’s type is fixed at compile time and never changes, you can store it directly without std::function.

Suppose you’re writing a task runner class that stores a single callable:

template <typename Callable>
class TaskRunner {
public:
TaskRunner(Callable c) : func_(std::move(c)) {}

void run() {
func_();
}

private:
Callable func_;
};

int main() {
TaskRunner task_runner([]() {
std::cout << "Callable called!" << std::endl;
});
task_runner.run();
}

Here, we use a class template to store the callable as a member by its exact type. Since the type is known and doesn’t change, there’s no need for runtime polymorphism.

Now compare with a std::function version:

class TaskRunner {
public:
template <typename Callable>
TaskRunner(Callable c) : func_(std::move(c)) {}

void run() {
func_();
}

private:
std::function<void()> func_;
};

Functionally, this version is equivalent but we are paying for flexibility we do not use. The callable is set once during construction and never changes.

What’s the overhead of std::function?

The main cost of std::function is due to:

  • Invoking a callable through std::function becomes an indirect call (which adds unnecessary overhead if your use case allows a statically dispatched function call).
  • std::function may dynamically allocate if the stored callable is large.

Let’s take a look at how std::function is implemented to better understand these costs.

Implementing a simplified std::function

We’ll implement a minimal version of std::function, which I’ll call SimpleFunction. It should behave similarly to std::function:

SimpleFunction<int(int, int)> my_func = [](int x, int y) {
return x + y;
};

To start, we know that the type signature of SimpleFunction must be templated on a return type R and an arbitrary number of argument types Args…. We can do this using template partial specialization:

template <typename>
struct SimpleFunction;

template <typename R, typename... Args>
struct SimpleFunction<R(Args...)> {
// To implement
};

We also know what the interface of SimpleFunction looks like. It should:

  • Accept any callable type F (function pointer, lambda, functor) in the constructor.
  • Provide operator() to invoke the stored callable.

So we extend our skeleton:

template <typename>
struct SimpleFunction;

template <typename R, typename... Args>
struct SimpleFunction<R(Args...)> {

// Constructor
// F is arbitrary callable type (function ptr, lambda, etc.)
template <typename F>
SimpleFunction(F&& f) {
// To implement
}

R operator()(Args... args) const {
// To implement
}
};

The challenge now is: how do we store this arbitrary type F (passed into the constructor in SimpleFunction) while still keeping F out of the type signature of SimpleFunction?

This is where type erasure comes into play.

Get Ng Song Guan’s stories in your inbox

Join Medium for free to get updates from this writer.

We’ll implement type erasure using a virtual interface. We define an abstract base class called CallableBase. SimpleFunction will store a pointer to this base which hides a concrete implementation.

template <typename>
struct SimpleFunction;

template <typename R, typename... Args>
struct SimpleFunction<R(Args...)> {

// Abstract interface to aid in type erasure.
// We will define a conrete struct to inherit from this later
// which will store F.
struct CallableBase {
virtual R invoke(Args&&... args) = 0;
virtual ~CallableBase() = default;
};

// Constructor
// F is arbitrary callable type (function ptr, lambda, etc.)
template <typename F>
SimpleFunction(F&& f) {
// To implement
}

R operator()(Args... args) const {
return ptr_->invoke(std::forward<Args>(args)...);
}

private:
// F will be 'hidden' in CallableBase behind this pointer.
std::unique_ptr<CallableBase> ptr_;
};

Now we define a concrete implementation CallableImpl<F> that inherits from CallableBase and stores the actual callable:

#pragma once
#include <utility>
#include <memory>
#include <stdexcept>

template <typename>
struct SimpleFunction;

template <typename R, typename... Args>
struct SimpleFunction<R(Args...)> {

// Abstract interface to aid in type erasure.
struct CallableBase {
virtual R invoke(Args&&... args) = 0;
virtual ~CallableBase() = default;
};

// Concrete implementation of interface, stores F to be invoked later.
template <typename F>
struct CallableImpl : CallableBase {
CallableImpl(F f) : functor(std::move(f)) {}

R invoke(Args&&... args) override {
return functor(std::forward<Args>(args)...);
}
private:
F functor;
};

// Constructor
// F is arbitrary callable type (function ptr, lambda, etc.)
template <typename F>
SimpleFunction(F&& f) {
// Use std::decay_t to remove refs and cv qualifiers
using DecayedF = std::decay_t<F>;
// Create CallableImpl which is stored 'behind' CallableBase
ptr_ = std::make_unique<CallableImpl<DecayedF>>(std::forward<F>(f));
}

R operator()(Args... args) const {
return ptr_->invoke(std::forward<Args>(args)...);
}

// TODO: Implement copy/move operations

private:
std::unique_ptr<CallableBase> ptr_;
};

How it works

When operator() is called:

  1. It calls the virtual invoke() method on CallableBase.
  2. Dynamic dispatch calls CallableImpl<F>::invoke().
  3. This invokes the stored callable F.

That’s it, we’ve implemented the core idea of std::function. Using a virtual interface, we erased the type of the callable. This is similar to Clang’s implementation (libc++) of std::function.

Runtime costs of SimpleFunction

Heap allocation

In SimpleFunction, we use std::unique_ptr to store the callable F.

std::unique_ptr<CallableBase> ptr_;

This means every SimpleFunction construction allocates heap memory to store the callable. This is necessary because the type F can be of arbitrary size:

  • If F is a simple function pointer, it's usually 8 bytes on a 64-bit system.
  • But if F is a capturing lambda or a large function object, it can be much bigger.

Real std::function implementations reduce heap allocations with Small Buffer Optimization (SBO) — similar to how Small String Optimization (SSO) works in std::string. If the callable F fits in a fixed-size internal buffer, it is stored in-place; otherwise, the implementation falls back to the heap.

I wrote a small Google Benchmark to demonstrate this behavior and to find the SBO threshold for my Clang compiler:

--------------------------------------------------------------------------
Benchmark Time CPU Iterations UserCounters...
--------------------------------------------------------------------------
BM_SBO_Size<0> 9.77 ns 9.75 ns 73438385 new_calls=0
BM_SBO_Size<8> 10.2 ns 10.2 ns 67428935 new_calls=0
BM_SBO_Size<16> 10.0 ns 10.0 ns 70541050 new_calls=0
BM_SBO_Size<24> 22.1 ns 22.1 ns 31923384 new_calls=1
BM_SBO_Size<32> 24.3 ns 24.2 ns 29114140 new_calls=1
BM_SBO_Size<40> 23.8 ns 23.8 ns 29190871 new_calls=1

Sweeping across lambda capture sizes shows a jump in latency of std::function construction (and one heap allocation) when going from 16 bytes to 24 bytes captures. This matches the 16 bytes SBO buffer size we can see in the code of Clang’s std::function implementation.

Virtual dispatch cost

operator() in SimpleFunction uses virtual function dispatch:

R operator()(Args... args) const {
return ptr_->invoke(std::forward<Args>(args)...);
}

A virtual function call is an indirect call through a vtable. Since the target function isn’t known at compile time, the compiler generally can’t inline it², which reduces opportunities for other optimizations. Indirect calls also increase the risk of instruction cache misses and CPU branch mis-predictions at runtime.

By contrast, statically dispatched calls (where the destination is known at compile time) allows for more optimizations by the compiler and is easier on the CPU.

Alternative SimpleFunction implementation

Type erasure in C++ doesn’t have to use virtual functions and inheritance. We can also implement it using the C-style method — storing the callable as a void*.

Press enter or click to view image in full size

The general idea is we store:

  • A void* pointing to the callable.
  • An invoker_ function pointer that knows how to cast this void* back to the original type and call it.

We start with a basic skeleton:

template<typename>
struct SimpleFunction;

template<typename R, typename... Args>
struct SimpleFunction<R(Args...)> {

template<typename F>
SimpleFunction(F&& f) {
// To implement
// Store F as a void* in ptr_
// Set up invoker_ which knows how to call ptr_
}

R operator()(Args... args) const {
// Call the stored F via invoker_
return invoker_(ptr_, std::forward<Args>(args)...);
}

private:
void* ptr_ = nullptr;

using InvokerFn = R(*)(void*, Args&&...);
InvokerFn invoker_ = nullptr;
};

We now implement the constructor to store F on the heap and set the invoker_ function pointer:

template <typename F>
SimpleFunction(F&& f) {
using DecayedF = std::decay_t<F>;
ptr_ = new DecayedF(std::forward<F>(f));

invoker_ = [](void* ptr, Args&&... args) -> R {
return (*static_cast<DecayedF*>(ptr))(std::forward<Args>(args)...);
};
}

We get type erasure by storing F via void* ptr_ , so F once again doesn’t appear in SimpleFunction’s type signature.

Finally, we also add a deleter function pointer to free the heap memory we allocated.

Full example:

template<typename>
struct SimpleFunction;

template<typename R, typename... Args>
struct SimpleFunction<R(Args...)> {

template<typename F>
SimpleFunction(F&& f) {
using DecayedF = std::decay_t<F>;
// Allocate space for F
ptr_ = new DecayedF(std::forward<F>(f));

// Set up invoker_
invoker_ = [](void* ptr, Args&&... args) -> R {
return (*static_cast<DecayedF*>(ptr))(std::forward<Args>(args)...);
};

// Set up deleter_
deleter_ = [](void* ptr) {
delete static_cast<DecayedF*>(ptr);
};
}

~SimpleFunction() {
if (ptr_ && deleter_) {
deleter_(ptr_);
}
}

// TODO: Implement copy and move operations

R operator()(Args... args) const {
return invoker_(ptr_, std::forward<Args>(args)...);
}

private:
void* ptr_ = nullptr;

using InvokerFn = R(*)(void*, Args&&...);
using DeleterFn = void(*)(void*);
InvokerFn invoker_ = nullptr;
DeleterFn deleter_ = nullptr;
};

This method avoids virtual functions, but we are still performing indirect calls. In practice, both approaches are very close in performance. GCC’s implementation (libstdc++) uses this style of type erasure for std::function.

In-place std::function

Our earlier SimpleFunction implementations always perform a heap allocation to store the callable. std::function may avoid this via SBO, but it can still allocate dynamically if the callable is too large.

In performance-critical code, any dynamic allocation can be too expensive. For such use cases, we can eliminate it entirely by storing the callable in-place in a fixed-size buffer, and never allow heap fallback. If the callable is too large, compilation simply fails.

Here’s the adjusted SimpleFunction which uses in-place storage:

template<typename, size_t = 1024>
struct SimpleFunction;

template<typename R, typename... Args, size_t CAPACITY>
struct SimpleFunction<R(Args...), CAPACITY> {

template<typename F>
SimpleFunction(F&& f) {
using DecayedF = std::decay_t<F>;
// Check that our buffer can fit F at compile time
static_assert(sizeof(DecayedF) <= BUF_CAP, "Callable too large for in-place buffer");
static_assert(alignof(DecayedF) <= alignof(std::max_align_t), "Alignment mismatch");
// placement new into our buffer
ptr_ = new (buffer_) DecayedF(std::forward<F>(f));

invoker_ = [](void* ptr, Args&&... args) -> R {
return (*static_cast<DecayedF*>(ptr))(std::forward<Args>(args)...);
};

deleter_ = [](void* ptr) {
static_cast<DecayedF*>(ptr)->~DecayedF();
};
}

~SimpleFunction() {
if (ptr_ && deleter_) {
// call destructor
deleter_(ptr_);
}
}

// TODO: Implement copy and move operations

R operator()(Args... args) const {
if (!invoker_) {
throw std::runtime_error("bad function call");
}
return invoker_(ptr_, std::forward<Args>(args)...);
}

private:
void* ptr_ = nullptr;

using InvokerFn = R(*)(void*, Args&&...);
using DeleterFn = void(*)(void*);
InvokerFn invoker_ = nullptr;
DeleterFn deleter_ = nullptr;

static constexpr size_t BUF_CAP = CAPACITY - sizeof(ptr_)
- sizeof(invoker_) - sizeof(deleter_);
// fixed-size inplace buffer
alignas(std::max_align_t) char buffer_[BUF_CAP];
};

Example usage:

void func() {
SimpleFunction<void(), 100> inplace_f = []{
do_something();
});
inplace_f();
}

Notes

  • This approach completely avoids heap allocation.
  • The fixed-size buffer means you must choose CAPACITY carefully to suit your use case.
  • If the callable is too large to fit in-place, you get a compile-time error via the static_assert.

There exists stdext::inplace_function, which is a proposed standard extension providing similar guarantees with richer functionality.

To sum up, std::function is a type-erased, owning wrapper for any callable, offering flexibility at the cost of some performance. We’ve seen some possible design choices but there are actually many more. Looking ahead, the C++ standard library is adding more callable wrappers to cover different use cases:

  • std::function_ref (C++26) is a non-owning, lightweight reference to an existing callable, analogous to std::string_view vs std::string .
  • std::move_only_function (C++23) and std::copyable_function (C++26). These gives developers finer control over performance and ownership semantics.

My complete SimpleFunction implementations with copy/move operations support can be found here: https://github.com/sgn00/sgfunction.

[1] The compiler can inline and optimize std::function in some cases. In this simple example, when compiling with Clang on -O3, both run_task functions produced similar assembly.

[2] In some cases, the compiler can devirtualize virtual function calls, eliminating their runtime overhead.

--