| 1 |
// { dg-do run } |
| 2 |
// { dg-skip-if "requires hosted libstdc++ for iostream" { ! hostedlib } } |
| 3 |
/* |
| 4 |
Test that instances created in capture clauses within co_await statements do not |
| 5 |
get 'promoted'. This would lead to the members destructor getting called more |
| 6 |
than once. |
| 7 |
|
| 8 |
Correct output should look like: |
| 9 |
Foo(23) 0xf042d8 |
| 10 |
Foo(const& 23) 0xf042ec |
| 11 |
~Foo(23) 0xf042ec |
| 12 |
After co_await |
| 13 |
~Foo(23) 0xf042d8 |
| 14 |
*/ |
| 15 |
#include <coroutine> |
| 16 |
#include <iostream> |
| 17 |
|
| 18 |
static unsigned int struct_Foo_destructor_counter = 0; |
| 19 |
static bool lambda_was_executed = false; |
| 20 |
|
| 21 |
class Task { |
| 22 |
public: |
| 23 |
struct promise_type { |
| 24 |
Task get_return_object() { |
| 25 |
return {std::coroutine_handle<promise_type>::from_promise(*this)}; |
| 26 |
} |
| 27 |
|
| 28 |
std::suspend_never initial_suspend() { return {}; } |
| 29 |
std::suspend_always final_suspend() noexcept { return {}; } |
| 30 |
void unhandled_exception() {} |
| 31 |
void return_void() {} |
| 32 |
}; |
| 33 |
|
| 34 |
~Task() { |
| 35 |
if (handle_) { |
| 36 |
handle_.destroy(); |
| 37 |
} |
| 38 |
} |
| 39 |
|
| 40 |
bool await_ready() { return false; } |
| 41 |
bool await_suspend(std::coroutine_handle<>) { return false; } |
| 42 |
bool await_resume() { return false; } |
| 43 |
|
| 44 |
private: |
| 45 |
Task(std::coroutine_handle<promise_type> handle) : handle_(handle) {} |
| 46 |
|
| 47 |
std::coroutine_handle<promise_type> handle_; |
| 48 |
}; |
| 49 |
|
| 50 |
class Foo { |
| 51 |
public: |
| 52 |
Foo(int id) : id_(id) { |
| 53 |
std::cout << "Foo(" << id_ << ") " << (void*)this << std::endl; |
| 54 |
} |
| 55 |
|
| 56 |
Foo(Foo const& other) : id_(other.id_) { |
| 57 |
std::cout << "Foo(const& " << id_ << ") " << (void*)this << std::endl; |
| 58 |
} |
| 59 |
|
| 60 |
Foo(Foo&& other) : id_(other.id_) { |
| 61 |
std::cout << "Foo(&& " << id_ << ") " << (void*)this << std::endl; |
| 62 |
} |
| 63 |
|
| 64 |
~Foo() { |
| 65 |
std::cout << "~Foo(" << id_ << ") " << (void*)this << std::endl; |
| 66 |
struct_Foo_destructor_counter++; |
| 67 |
|
| 68 |
if (struct_Foo_destructor_counter > 2){ |
| 69 |
std::cout << "Foo was destroyed more than two times!\n"; |
| 70 |
__builtin_abort(); |
| 71 |
} |
| 72 |
} |
| 73 |
|
| 74 |
private: |
| 75 |
int id_; |
| 76 |
}; |
| 77 |
|
| 78 |
Task test() { |
| 79 |
Foo foo(23); |
| 80 |
|
| 81 |
co_await [foo]() -> Task { // A copy of foo is captured. This copy must not get 'promoted'. |
| 82 |
co_return; |
| 83 |
}(); |
| 84 |
|
| 85 |
std::cout << "After co_await\n"; |
| 86 |
if (struct_Foo_destructor_counter == 0){ |
| 87 |
std::cout << "The captured copy of foo was not destroyed after the co_await statement!\n"; |
| 88 |
__builtin_abort(); |
| 89 |
} |
| 90 |
} |
| 91 |
|
| 92 |
int main() { |
| 93 |
test(); |
| 94 |
return 0; |
| 95 |
} |