【问题标题】:boost::iostreams sink device: Why does this trivial test code crash?boost::iostreams sink device:为什么这个微不足道的测试代码会崩溃?
【发布时间】:2018-03-27 20:02:35
【问题描述】:

我正在尝试熟悉如何使用 boost::iostreams。查看 iostreams 教程,似乎这个测试代码应该是接收设备和流模板的简单实现:

#include <iostream>
#include <iosfwd>

#include <boost/iostreams/categories.hpp>
#include <boost/iostreams/stream.hpp>
#include <boost/iostreams/concepts.hpp>

namespace io = boost::iostreams;

class testSink {
public:
    typedef char            char_type;
    typedef io::sink_tag    category;

    std::streamsize write(const char* s, std::streamsize n) {
        std::cout.write(s, n);
        return n;
    }
};

int main(int argc, char *argv[])
{
    io::stream<testSink>    out;
    out << "Hello" << std::endl;
    return EXIT_SUCCESS;
}

在 linux 和 g++ (g++ (GCC) 4.8.5 20150623 (Red Hat 4.8.5-16)) 下编译它成功且没有错误,但运行它会因断言失败而崩溃:

/usr/local/include/boost/iostreams/detail/optional.hpp:55: T& boost::iostreams::detail::optional::operator*() [with T = boost::iostreams::detail ::concept_adapter]:断言“初始化_”失败。 中止(核心转储)

显然有一些未记录的初始化步骤,但是什么?

谢谢

【问题讨论】:

    标签: c++ boost-iostreams


    【解决方案1】:

    缺少的初始化步骤是调用“open”。 boost 文档对此似乎不太清楚——我从阅读源代码中发现了这一点。事实上,我正在使用的文档中的示例 (1.55) 与您面临的问题相同。

    以下是我为您修改 testSink 的方法:我添加了一个构造函数,该构造函数引用一个 ostream,然后将 std::cout 传递给 open() 方法。

    class testSink {
    public:
        typedef char            char_type;
        typedef io::sink_tag    category;
    
        testSink(std::ostream &out) : out_(out) { }
    
        std::streamsize write(const char* s, std::streamsize n) {
            out_.write(s, n);
            return n;
        }
    
    private:
        std::ostream& out_;
    };
    

    然后这是主要功能:

    io::stream<testSink>    out;
    out.open(std::cout);
    out << "Hello" << std::endl;
    

    【讨论】:

    • 嗯。好的,也许我也会深入研究源代码。对于我最终的目标项目,我不希望传入 ostream 引用。我必须看看有哪些 open() 重载可用。感谢您的回复。
    【解决方案2】:

    我遇到了同样的问题,调用 non-default constructor of the stream object 传递一个接收器对象解决了它(根据文档,非默认构造函数创建一个准备执行 i/o 的流)。

    因此,您的示例适用于对 main 函数的以下更改:

    int main(int argc, char *argv[])
    {
        testSink t;
        io::stream<testSink>    out(t); // <---- call non-default constructor passing a testSink object
        out << "Hello" << std::endl;
        return EXIT_SUCCESS;
    }
    

    这是处理 Coliru 的示例。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-10-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-11
      相关资源
      最近更新 更多