Closed HWZen closed 1 year ago
By the way, the above code didn't work on both Windows and Linux
asio::co_spawn(co_await asio::this_coro::executor,
[command = std::move(command)]() mutable->asio::awaitable<void>{
co_await timeout(1s); // wait foo1's command to be destroyed
std::cout << command.DebugString() << std::endl;
std::cout.flush();
}() /*Added a pair of parentheses here */, asio::detached);
Eager coroutines will destroy lambda captures at the first suspension point.
Lazy ones will do this immediately.
You must use:
asio::co_spawn(co_await asio::this_coro::executor,
[](auto command) ->asio::awaitable<void> {
std::cout << command.DebugString() << std::endl;
std::cout.flush();
co_return;
}(std::move(command)), asio::detached);
Note, that I called the lambda with command
.
For a better explanation, see https://devblogs.microsoft.com/oldnewthing/20211103-00/?p=105870
Oh! lambda will be destoryed at the first suspension point?How insidious ! Thank you for answering my problom and the blog you shared.
the above code works in Windows MSVC19.33:
but not good in Linux gcc 12.2:
We can see that on MSVC and gcc, Data moved three times, but gcc destroyed Data three times before the end of foo1, one more than MSVC, and it was the last destruction that released the correct data. Is this the reason for the error?
Of cource I can use lambda like this:
That is works on both Windows and Linux.
But what about
this
? Does it also come as part of the parameters of the lambda function? I don't think it's very elegant.