1

for example: when I write this code I recieve right result.

boost::asio::thread_pool t(3);
std::vector<int> vec = {10,20,30};
boost::asio::post(t, [&]{ foo(vec[0]);});
boost::asio::post(t, [&]{ foo(vec[1]);});
boost::asio::post(t, [&]{ foo(vec[2]);});
t.join();

but when i want use boost::asio::post in for-cicle i recieve error Microsoft Visual C++ Runtime Library: "Expression: vector subscript out of range"

boost::asio::thread_pool t(3);
std::vector<int> vec = {10,20,30};
for (int i = 0; i < 3; ++i) {
    boost::asio::post(t, [&]{ foo(vec[i]);});
}
t.join();

what can i do to make my last way return the correct answer?

1 Answers1

5

You are capturing i by reference for a lambda that is used asynchronously. When t.join(); is reached, i is a dangling reference.

Capture it by value so it doesn't change or expire.

boost::asio::post(t, [&,i]{ foo(vec[i]);});
sehe
  • 374,641
  • 47
  • 450
  • 633
Drew Dormann
  • 59,987
  • 13
  • 123
  • 180