c++boost-asioc++-coroutine

Coroutine awaited in parameter list breaks another parameter?


I've got the following code

https://godbolt.org/z/nehcPdxGe

#include <boost/asio.hpp>
#include <boost/asio/awaitable.hpp>
#include <boost/asio/co_spawn.hpp>
#include <gtest/gtest.h>

template <typename FUNC, typename EXECUTOR> void foo(FUNC, EXECUTOR) {}

struct Marker {
    void const* ptr;
    Marker() : ptr(this) {}
    Marker(Marker const& rhs) = delete;
    ~Marker() { EXPECT_EQ(this, ptr); }
};

boost::asio::awaitable<int> xxx() { co_return 0; }

boost::asio::awaitable<void> test_in_coro() {
    foo([marker = Marker{}]() -> int { return 42; }, co_await xxx());
    co_return;
}

TEST(BugInCoro, Reproduce) {
    boost::asio::io_context ioc;
    boost::asio::co_spawn(ioc, test_in_coro(), boost::asio::detached);
    ioc.run();
}

int main() {
    testing::InitGoogleTest();
    return RUN_ALL_TESTS();
}

The assert in the destructor of Marker fails. Moreover, I've checked, that ptr is the same as in constructor, while this differs.

Everything works fine if I awakt before calling foo or store the lambda in a local variable.

It happens in gcc 11.x and 12.x but not in 13.x and not in clang.

Am I falling into some undefined behavior? Or maybe is it a compiler bug?


Solution

  • Yes, this is a compiler issue. It was fixed in GCC13.

    Best I can find it was fixed in https://gcc.gnu.org/git/gitweb.cgi?p=gcc.git;h=58a7b1e354530d8dfe7d8fb859c8b8b5a9140f1f

    coroutines: Do not promote temporaries that will be elided.
    
    We usually need to 'promote' (i.e. save to the coroutine frame) any temporary
    variable that is in a target expression that must persist across an await
    expression.  However, if the TE is just used as a direct initializer for
    another object it will be elided - and we should not promote it since that
    would lead to a DTOR call for something that is never constructed.
    
    Since we now have a mechanism to tell if TEs will be elided, use that.
    
    Although the PRs referenced initially appear to be different issues, they all
    stem from this.
    
    Co-Authored-By: Adrian Perl <adrian.perl@web.de>
    Signed-off-by: Iain Sandoe <iain@sandoe.co.uk>
    PR c++/100611
    PR c++/101367
    PR c++/101976
    PR c++/99576
    
    gcc/cp/ChangeLog:
    
    * coroutines.cc (find_interesting_subtree): Do not promote temporaries
    that are only used as direct initializers for some other object.
    
    gcc/testsuite/ChangeLog:
    
    * g++.dg/coroutines/pr100611.C: New test.
    * g++.dg/coroutines/pr101367.C: New test.
    * g++.dg/coroutines/pr101976.C: New test.
    * g++.dg/coroutines/pr99576_1.C: New test.
    * g++.dg/coroutines/pr99576_2.C: New test.
    

    You can look at any of the mentioned bug links for more information and to see that some of the reproducers are basically identical to yours, except not using Asio promise types.