<分区>
可重复的例子:
#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)
那么一切正常吗?