Why can't co_await return a string?

Viewed 260
#include <coroutine>
#include <string>

template<typename T>
struct Awaiter final {
    bool await_ready() const { return false; }    
    void await_suspend(std::coroutine_handle<>) const {}    
    T await_resume() const { return T{}; }
};

struct ReturnObject {
  struct promise_type {
    ReturnObject get_return_object() { return {}; }
    std::suspend_never initial_suspend() 
        noexcept { return {}; }
    std::suspend_never final_suspend() 
        noexcept { return {}; }
    void return_void() {}
    void unhandled_exception() {}
  };
};

ReturnObject f()
{
    auto a1 = Awaiter<int>{};
    [[maybe_unused]] auto v1 = co_await a1; // ok    
    auto a2 = Awaiter<std::string>{};
    [[maybe_unused]] auto v2 = co_await a2; // error
}

int main() { f(); }

See: online demo

The error message:

error: no suspend point info for ''co_await' not supported 
       by dump_decl<declaration error>'
   37 |     [[maybe_unused]] auto v2 = co_await a2; // error
      |                                ^~~~~~~~

Why can't co_await return a string?

2 Answers

This is a compiler bug in the implementation of coroutines in GCC, as there is nothing in the current drafts of the standard prohibiting custom/composite types for await_resume (as can be seen when replacing string with any user-defined type). The very same code for example compiles with the latest version of MSVC using the /std:c++latest flag (which is no surprise, as Gor Nishanov, who prominently develops on the draft, uses Visual Studio to implement a prototype which may be the most tested implementation at the time of writing of this answer).

I was struggling with this bug as well and found a workaround that can be handy for anyone stuck with gcc 11. The trick is to add await_transform to the promise, this seem to fix the issue:

template <typename U>
U&& await_transform(U&& awaitable) noexcept
{
    return static_cast<U&&>(awaitable);
}

See https://godbolt.org/z/aTMYMfav4

Related