C ++ 11 lambda capture list [=] use link

When I commit a value, but the type of the value 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);
}

he prints

2
3
2

But in T t1(t); Tthere int&, so it t1should be int&when the lambda calls test(t1). Why is there no way out?

2
3
3
+5
source share
2 answers

T is int & therefore t1 must be int &

Links are not pointers. Tcan be inferred as int&, therefore, t1is a link. But you asked lambda to commit t1by value. This means copying the value referenced t1.

t1 , . " "; .

+7

[=] t1, test(), , t1 , t.

+2

All Articles