Debian Codegraph @

gcc/testsuite/g++.dg/coroutines/pr101976.C

raw
1 // { dg-do run }
2 // { dg-skip-if "requires hosted libstdc++ for iostream" { ! hostedlib } }
3
4 /*
5 Test that members of temporary instances in co_await statements do not get
6 'promoted'. This would lead to the members destructor getting called more
7 than once.
8
9 Correct output should look like:
10 Before co_await
11 nontrivial_move() 0x6ec2e1
12 nontrivial_move(nontrivial_move&&) 0x6ed320
13 In subtask
14 ~nontrivial_move() 0x6ed320
15 ~nontrivial_move() 0x6ec2e1
16 After co_await
17 */
18 #include <coroutine>
19 #include <iostream>
20
21 static unsigned int struct_nontrivial_move_destructor_counter = 0;
22
23 struct task {
24 struct promise_type {
25 task get_return_object() {
26 return {std::coroutine_handle<promise_type>::from_promise(*this)};
27 }
28 std::suspend_never initial_suspend() { return {}; }
29 std::suspend_never final_suspend() noexcept { return {}; }
30 void unhandled_exception() {}
31 void return_void() {}
32 };
33
34 bool await_ready() { return true; }
35 void await_suspend(std::coroutine_handle<>) {}
36 void await_resume() {}
37
38 std::coroutine_handle<promise_type> m_handle;
39 };
40
41 struct nontrivial_move {
42 nontrivial_move() {
43 std::cout << "nontrivial_move() " << (void *)this << std::endl;
44 }
45 nontrivial_move(nontrivial_move&&) {
46 std::cout << "nontrivial_move(nontrivial_move&&) " << (void *)this
47 << std::endl;
48 }
49 ~nontrivial_move() {
50 std::cout << "~nontrivial_move() " << (void *)this << std::endl;
51 struct_nontrivial_move_destructor_counter++;
52 if (struct_nontrivial_move_destructor_counter > 2){
53 std::cerr << "The destructor of nontrivial_move was called more than two times!\n";
54 __builtin_abort();
55 }
56 }
57
58 char buf[128]{}; // Example why the move could be non trivial
59 };
60
61 struct wrapper {
62 nontrivial_move member;
63 };
64
65 task subtask(wrapper /* unused */) {
66 std::cout << "In subtask\n";
67 co_return;
68 }
69
70 task main_task() {
71 std::cout << "Before co_await\n";
72 co_await subtask({}); // wrapper must get 'promoted', but not its member
73 std::cout << "After co_await\n";
74 }
75
76 int main() {
77 main_task();
78 return 0;
79 }