Debian Codegraph @

gcc/testsuite/g++.dg/coroutines/torture/co-ret-06-template-promise-val-1.C

raw
1 // { dg-do run }
2 // { dg-skip-if "requires hosted libstdc++ for cstdlib abort" { ! hostedlib } }
3
4 // Test returning a T.
5 // We will use the promise to contain this to avoid having to include
6 // additional C++ headers.
7
8 #include "../coro.h"
9
10 struct suspend_never_prt {
11 bool await_ready() const noexcept { return true; }
12 void await_suspend(coro::coroutine_handle<>) const noexcept
13 { PRINT ("susp-never-susp"); }
14 void await_resume() const noexcept { PRINT ("susp-never-resume");}
15 };
16
17 /* NOTE: this has a DTOR to test that pathway. */
18 struct suspend_always_prt {
19 bool await_ready() const noexcept { return false; }
20 void await_suspend(coro::coroutine_handle<>) const noexcept
21 { PRINT ("susp-always-susp"); }
22 void await_resume() const noexcept { PRINT ("susp-always-resume"); }
23 ~suspend_always_prt() { PRINT ("susp-always-DTOR"); }
24 };
25
26 template <typename T>
27 struct coro1 {
28 struct promise_type;
29 using handle_type = coro::coroutine_handle<coro1::promise_type>;
30 handle_type handle;
31 coro1 () : handle(0) {}
32 coro1 (handle_type _handle)
33 : handle(_handle) {
34 PRINT("Created coro1 object from handle");
35 }
36 coro1 (const coro1 &) = delete; // no copying
37 coro1 (coro1 &&s) : handle(s.handle) {
38 s.handle = nullptr;
39 PRINT("coro1 mv ctor ");
40 }
41 coro1 &operator = (coro1 &&s) {
42 handle = s.handle;
43 s.handle = nullptr;
44 PRINT("coro1 op= ");
45 return *this;
46 }
47 ~coro1() {
48 PRINT("Destroyed coro1");
49 if ( handle )
50 handle.destroy();
51 }
52
53 struct promise_type {
54 T value;
55 promise_type() { PRINT ("Created Promise"); }
56 ~promise_type() { PRINT ("Destroyed Promise"); }
57
58 auto get_return_object () {
59 PRINT ("get_return_object: handle from promise");
60 return handle_type::from_promise (*this);
61 }
62
63 auto initial_suspend () const {
64 PRINT ("get initial_suspend (always)");
65 return suspend_always_prt{};
66 }
67 auto final_suspend () const noexcept {
68 PRINT ("get final_suspend (always)");
69 return suspend_always_prt{};
70 }
71 void return_value (T v) {
72 PRINTF ("return_value () %d\n",v);
73 value = v;
74 }
75 T get_value (void) { return value; }
76 void unhandled_exception() { PRINT ("** unhandled exception"); }
77 };
78 };
79
80 coro1<float>
81 f () noexcept
82 {
83 PRINT ("coro1: about to return");
84 co_return (float) 42;
85 }
86
87 int main ()
88 {
89 PRINT ("main: create coro1");
90 coro1<float> x = f ();
91 PRINT ("main: got coro1 - resuming");
92 if (x.handle.done())
93 abort();
94 x.handle.resume();
95 PRINT ("main: after resume");
96 int y = x.handle.promise().get_value();
97 if ( y != (float)42 )
98 abort ();
99 if (!x.handle.done())
100 {
101 PRINT ("main: apparently not done...");
102 abort ();
103 }
104 PRINT ("main: returning");
105 return 0;
106 }