This question already has an answer here:
- Can a local variable's memory be accessed outside its scope? 20 answers
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?