user1625647
user1625647

Reputation: 113

C++11 lambda capture list [=] use a reference

When I capture a value but the value type is a reference in a template function

template<class T>
void test(T&&i)
{
    ++i;
    std::cout << i << std::endl;
}

template<class T>
void typetest(T&& t)
{
    ++t;
    T t1(t);
    [=]() mutable { std::cout << t1 << std::endl; return test(t1); }();
    std::cout << t << std::endl;
}

int main()
{
    int i=1;
    typetest(i);
}

it prints

2
3
2

But in T t1(t); T is int& so t1 should be int& when the lambda calls test(t1). Why is the output not

2
3
3

Upvotes: 5

Views: 649

Answers (2)

Nicol Bolas
Nicol Bolas

Reputation: 473457

T is int& so t1 should be int&

References are not pointers. T may be deduced as int&, thus t1 is a reference. But you asked the lambda to capture t1 by value. That means copying the value referenced by t1.

If t1 were a pointer, you would get the pointer by value. But you can't get a reference "by value"; you can only get the value being referenced.

Upvotes: 7

Ben Cottrell
Ben Cottrell

Reputation: 6120

Through capture-by-value [=] your lambda obtains a local copy of t1 which it passes to test(), so whatever happens to t1 in the lambda will never affect the original t object.

Upvotes: 2

Related Questions