c++ - Boost协程断言失败

标签 c++ boost boost-coroutine

为了在 boost 中尝试新的协程功能,我创建了以下程序:

#include <boost/coroutine/all.hpp>
#include <string>
#include <vector>


typedef boost::coroutines::coroutine<int(char)> coroutine_t;


void f(coroutine_t::caller_type & ca)
{
    std::vector<int> vec = {1, 2, 3};
    for (int i : vec)
    {
        char c = ca.get();
        std::cout << "c: " << c << std::endl;
        ca(i);
    }
}

int main()
{
    coroutine_t cr(f);
    std::string str("abc");
    for (char c : str)
    {
        std::cout << c << std::flush;
        cr(c);
        int n = cr.get();
        std::cout << n << std::endl;        
    }
}

代码基于sample code from the docs .

我的构建命令如下:

$ g++ -std=c++11 -o test -I/usr/local/include -L/usr/local/lib main.cpp /usr/local/lib/libboost_context.a

输出:

$ ./test
test: /usr/local/include/boost/coroutine/detail/coroutine_get.hpp:43: typename boost::coroutines::detail::param<Result>::type boost::coroutines::detail::coroutine_get<D, Result, arity>::get() const [with D = boost::coroutines::coroutine<char(int), 1>; Result = char; int arity = 1; typename boost::coroutines::detail::param<Result>::type = char]: Assertion `static_cast< D const* >( this)->impl_->result_' failed.
Aborted (core dumped)

程序因断言失败而中止。你能帮我找出代码中的错误吗?

最佳答案

我认为您需要在函数 f 的开头添加调用 ca()

来自 boost 文档:

The execution control is transferred to coroutine at construction (coroutine-function entered) - when control should be returned to the original calling routine, invoke boost::coroutines::coroutine<>::operator() on the first argument of type boost::coroutines::coroutine<>::caller_type inside coroutine-function.

关于c++ - Boost协程断言失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14707860/

相关文章:

c++ - 函数可以接受静态函数指针作为参数吗?

c++ - Visual Studio 2013 dll 导出链接错误 (LNK2019/LNK1120)

c++ - 我如何在这里为 union 内的结构赋值?

c++ - 如何使用 boost XML 存档序列化 OpenCV Mat

c++ - 使用用户定义的类和 int 创建 vector 在 ‘struct std::_Vector_base....no type named ‘value_type’ 中的 ‘class MyClass’ 的实例化

c++ - 我可以将 boost::make_shared 与私有(private)构造函数一起使用吗?

c++ - cmake 不使用 boost 多线程库

c++ - 如何让协程始终在同一个线程中工作?

c++ - 使用 Boost Coroutine(1.55) 的段错误不明确?