Post

std::bind and std::reference_wrapper

std::bind and std::reference_wrapper

std::bind and std::reference_wrapper


Prerequisites


1. What is a ‘std::bind’?

std::bind is a utility that allows you to bind arguments to a function and create a new callable object.

1
2
3
#include <functional>

auto f = std::bind(function, args...);

It transforms a function into a callable object with fixed or rearranged arguments

Use it when:

  • You need compatibility with older APIs
  • You want quick argument binding (rare nowadays)

Otherwise → use lambda

Example
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>
#include <functional>

int add(int a, int b)
{
    return a + b;
}

int main()
{
    auto f = std::bind(add, 2, 3);

    std::cout << f();  // 5
}

Arguments are pre-bound

1-1. Placeholders (std::placeholders)

Used to represent arguments that will be passed later.

1
2
3
4
5
using namespace std::placeholders;

auto f = std::bind(add, _1, 10); // auto f = std::bind(add, std::placeholder::_1, 10);

std::cout << f(5);  // 15

_1, _2, … are placeholders

Argument Reordering

1
2
3
auto f = std::bind(add, _2, _1);

std::cout << f(3, 5);  // 8 (5 + 3)

1-2. Binding Member Functions

1
2
3
4
5
6
7
8
9
10
11
12
13
struct MyClass
{
    int multiply(int a, int b)
    {
        return a * b;
    }
};

MyClass obj;

auto f = std::bind(&MyClass::multiply, &obj, 2, 3);

std::cout << f();  // 6

1-3. Common Pitfall: Copy vs Reference

1
2
3
4
5
6
7
8
9
10
int x = 10;

auto f = std::bind([](int v)
{
    std::cout << v;
}, x);

x = 20;

f();  // prints 10 ❗

std::bind copies arguments by default

1-4. Performance Considerations

- std::bind vs Lambda
std::bind
  • More complex
  • Harder to optimize
  • Less readable
1
auto f = std::bind(add, _1, 10);
1
2
3
4
auto f = [](int x)
{
    return add(x, 10);
};
Modern compilers:
  • Inline aggressively
  • Generate better code

Lambda is:

  • clearer
  • faster
  • preferred in modern C++
Performance Comparison
MethodPerformanceReadability
Lambda🔥 Fast✅ High
std::bind⚡ Medium❌ Low

2. What is std::reference_wrapper?

std::reference_wrapper allows you to store references inside standard containers or bind

1
2
3
#include <functional>

std::reference_wrapper<int> ref = x;

It behaves like a reference but is copyable

Use it when:

  • You need to store references in containers
1
std::vector<std::reference_wrapper<int>> v;
  • You need reference semantics in std::bind or std::function

✔️ Fixing the Copy Issue

1
2
3
4
5
6
7
8
9
10
int x = 10;

auto f = std::bind([](int& v)
{
    std::cout << v;
}, std::ref(x));

x = 20;

f();  // prints 20 ✅

std::ref(x) ensures reference semantics

std::ref and std::cref

FunctionDescription
std::ref(x)reference
std::cref(x)const reference
This post is licensed under CC BY 4.0 by the author.