为什么在lambda中通过引用捕获的值被破坏了? [英] Why value captured by reference in lambda is broken?

查看:148
本文介绍了为什么在lambda中通过引用捕获的值被破坏了?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

重复示例:

  #include< iostream> 
#include< boost / asio / io_service.hpp>

boost :: asio :: io_service io_service;

void test1(int t_a)
{
std :: cout< in test1:t_a =<< t_a < std :: endl;
}

void test2(int t_a)
{
std :: cout< in test2:t_a =<< t_a < std :: endl;

io_service.post([& t_a]()
{
std :: cout<<in test2 post lambda:t_a =< <<< std :: endl;
test1(t_a);
});
}

int main(int,char **)
{
int a = 42;

for(;;){
try
{
test2(a);
io_service.run();
break;
}
catch(std :: exception& e)
{

}
}
}



<$ p>

 
:t_a = 42
in test2 post lambda:t_a = 16451253
在test1中:t_a = 16451253
按任意键继续。 。 。

为什么?

int
这里只是举例,考虑任何不好的值通过的大对象(例如消耗性副本)



test1 test2 声明为 test1(const int& t_a) test2(const int& t_a)所有都工作正常吗?

解决方案

t_a 的参考仅在 void test2(int t_a) scope。
在你的情况下按价值捕获。


Repeatable example:

#include <iostream>
#include <boost/asio/io_service.hpp>

boost::asio::io_service io_service;

void test1(int t_a)
{
    std::cout << "in test1: t_a = " << t_a << std::endl;
}

void test2(int t_a)
{
    std::cout << "in test2: t_a = " << t_a << std::endl;

    io_service.post([&t_a]()
    {
        std::cout << "in test2 post lambda: t_a = " << t_a << std::endl;
        test1(t_a);
    });
}

int main(int, char**)
{
    int a = 42;

    for (;;) {
        try
        {
            test2(a);
            io_service.run();
            break;
        }
        catch (std::exception & e)
        {

        }
    }
}

Output:

in test2: t_a = 42
in test2 post lambda: t_a = 16451253
in test1: t_a = 16451253
Press any key to continue . . .

Why is that? Capturing by value is working as I expect it to, but why does capturing by reference behave like this?

Note int here is only for example, consider any big object which is bad to pass by value (expendable copy, for example)

Why if I declare test1 and test2 as test1(const int& t_a) and test2(const int& t_a) all is working correctly then?

解决方案

The reference of t_a is valid only in void test2(int t_a) scope. Capture by value in your case.

这篇关于为什么在lambda中通过引用捕获的值被破坏了?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆