【发布时间】:2015-09-14 18:54:06
【问题描述】:
可重复的例子:
#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)
{
}
}
}
输出:
in test2: t_a = 42
in test2 post lambda: t_a = 16451253
in test1: t_a = 16451253
Press any key to continue . . .
这是为什么呢?按值捕获按我的预期工作,但为什么按引用捕获会这样呢?
注意int这里只是举例,考虑任何不能传值的大对象(例如可消耗的副本)
如果我将test1 和test2 声明为test1(const int& t_a) 和test2(const int& t_a),那么为什么一切正常?
【问题讨论】:
-
您在其生命周期之外使用捕获的值,您可以找到类似的示例here
标签: c++ c++11 lambda boost-asio