简体   繁体   中英

Minimal awaitable example

I wonder why the following programme crashes. How to use awaitable not with boost::asio::async_write / async_read functions.

Let's see:

#include <iostream>

#include <boost/asio/io_context.hpp>
#include <boost/asio/co_spawn.hpp>
#include <boost/asio/detached.hpp>

using boost::asio::io_context;
using boost::asio::co_spawn;
using boost::asio::awaitable;
using boost::asio::detached;

awaitable<void> task() {
  std::cout << "hello" << std::endl;
  return awaitable<void>{};
}

int main() {
  try {
    boost::asio::io_context io_context(1);

    co_spawn(io_context, task(), detached);

    io_context.run();
  } catch(const std::exception &ex) {
    std::cerr << ex.what() << std::endl;
  }
  return 0;
}

This results in

hello
(Segmentation fault)

What is wrong about it?

UPD : self-solved. I should just use co_return . Thus it must be the following:

awaitable<void> task() {
  std::cout << "hello" << std::endl;
  co_return;
}

digging into the sources of boost::asio::awaitable , I figured out that I just should make use of co_return keyword. Surprisingly, it is not shipped with boost . It is enabled either by -fcoroutines flag or -std=c++20 . Unexpectedly. Having said that, it is solved.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM