Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 649
user1625647 Avatar asked Aug 26 '12 09:08

user1625647


1 Answers

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.

like image 100
Nicol Bolas Avatar answered Sep 30 '22 01:09

Nicol Bolas