| 1 |
// { dg-do run } |
| 2 |
// { dg-skip-if "requires hosted libstdc++ for iostream" { ! hostedlib } } |
| 3 |
/* |
| 4 |
Test that members of temporary awaitables in co_await statements do not get |
| 5 |
'promoted'. This would lead to the members destructor getting called more |
| 6 |
than once. |
| 7 |
|
| 8 |
Correct output should look like: |
| 9 |
A 0x4f82d6 |
| 10 |
~A 0x4f82d6 |
| 11 |
*/ |
| 12 |
#include <coroutine> |
| 13 |
#include <iostream> |
| 14 |
|
| 15 |
|
| 16 |
static unsigned int struct_A_destructor_counter = 0; |
| 17 |
|
| 18 |
struct task : std::coroutine_handle<> { |
| 19 |
struct promise_type; |
| 20 |
}; |
| 21 |
|
| 22 |
struct task::promise_type { |
| 23 |
task get_return_object() { |
| 24 |
return {std::coroutine_handle<promise_type>::from_promise(*this)}; |
| 25 |
} |
| 26 |
std::suspend_always initial_suspend() { return {}; } |
| 27 |
std::suspend_always final_suspend() noexcept { return {}; } |
| 28 |
void unhandled_exception() { std::terminate(); } |
| 29 |
void return_void() {} |
| 30 |
}; |
| 31 |
|
| 32 |
struct A { |
| 33 |
void log(const char *str) { std::cout << str << " " << (void *)this << std::endl; } |
| 34 |
|
| 35 |
A() { log(__func__); } |
| 36 |
|
| 37 |
~A() { |
| 38 |
log(__func__); |
| 39 |
struct_A_destructor_counter++; |
| 40 |
|
| 41 |
if (struct_A_destructor_counter > 1) { |
| 42 |
std::cout << "The destructor of A was called more than once!\n"; |
| 43 |
__builtin_abort(); |
| 44 |
} |
| 45 |
} |
| 46 |
|
| 47 |
A(A&&) = delete; |
| 48 |
A(A const&) = delete; |
| 49 |
A& operator=(A&&) = delete; |
| 50 |
A& operator=(A const&) = delete; |
| 51 |
}; |
| 52 |
|
| 53 |
struct Awaitable { |
| 54 |
A a{}; // <- This member must NOT get 'promoted' |
| 55 |
bool await_ready() { return false; } |
| 56 |
void await_suspend(std::coroutine_handle<> handle) {} |
| 57 |
void await_resume() {} |
| 58 |
}; |
| 59 |
|
| 60 |
task coroutine() { |
| 61 |
co_await Awaitable{}; // <- This temporary must get 'promoted' |
| 62 |
} |
| 63 |
|
| 64 |
int main() { |
| 65 |
|
| 66 |
auto task = coroutine(); |
| 67 |
while (!task.done()) { |
| 68 |
task(); |
| 69 |
} |
| 70 |
task.destroy(); |
| 71 |
|
| 72 |
return 0; |
| 73 |
} |