繁体   English   中英

boost :: iostreams接收器设备:为什么这个琐碎的测试代码崩溃?

[英]boost::iostreams sink device: Why does this trivial test code crash?

我正在尝试熟悉使用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 ]:断言“ initialized_”失败。 中止(核心已弃用)

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

谢谢

缺少的初始化步骤是调用“打开”。 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;

我遇到了同样的问题,并通过接收器对象调用流对象非默认构造函数来解决它(根据文档,非默认构造函数创建了准备执行I / O的流)。

因此,您的示例对主要功能进行了以下更改:

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上工作的示例。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM