Quantcast
Channel: Active questions tagged gcc - Stack Overflow
Viewing all articles
Browse latest Browse all 22001

Compiler optimizes out the coroutine value

$
0
0

I have implemented two coroutines that uses the Resumable class:

#include <coroutine>#include <future>#include <iostream>class Resumable{public:    class promise_type    {    public:        auto initial_suspend()        {            return std::suspend_always();        }        auto final_suspend() noexcept        {            return std::suspend_always();        }        auto yield_value(const int& value)        {            value_ = value;            return std::suspend_always();        }        auto return_value(const int& value)        {            value_ = value;            return std::suspend_always();        }        auto get_return_object()        {            return std::coroutine_handle<promise_type>::from_promise(*this);        }        void unhandled_exception()        {        }    public:        int value_;    };public:    Resumable(std::coroutine_handle<promise_type> handle)        : handle_{ handle }    {    }    ~Resumable()    {        handle_.destroy();    }    int get()    {        if (!handle_.done())        {            handle_.resume();        }        return handle_.promise().value_;    }private:    std::coroutine_handle<promise_type> handle_;};Resumable generate(int a){    for (int i = 1; i < a; ++i)    {        co_yield i;    }    co_return 0;}Resumable n_generate(int a){    auto gen = generate(a);    for (auto value = gen.get(); value != 0; value = gen.get())    {        //std::cout << -value << std::endl; <-- uncommenting this fixes the problem         co_yield -value;    }    co_return 0;}int main(int argc, const char* argv[]){    auto gen_10 = n_generate(10);    for (auto value = gen_10.get(); value != 0; value = gen_10.get())    {        std::cout << value << std::endl;    }    return 0;}

The output for this code is empty.

If I uncomment the line marked line in n_generate, the output will be:

-1-1-2-2-3-3-4-4-5-5-6-6-7-7-8-8-9-9

How can I pass the negative values to main without printing them in n_generate function?

I am using gcc-10 on Ububtu 20.04.Additional flags in my makefile:

LDLIBS := -lstdc++CXXFLAGS := -g -std=c++2a -fcoroutines

Viewing all articles
Browse latest Browse all 22001

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>