我在玩boost::iostreams,并且用户指南讨论了过滤器“计数器”。因此,我尝试使用以下代码:

#include <iostream>
#include <boost/iostreams/filtering_stream.hpp>
#include <boost/iostreams/device/null.hpp>
#include <boost/iostreams/filter/counter.hpp>
namespace io = boost::iostreams;
int main()
{
    io::counter cnt;
    io::filtering_ostream out(cnt | io::null_sink());
    out << "hello";
    std::cout << cnt.lines() << " " << cnt.characters() << std::endl;
}

它总是给
0 0

这似乎不是我所期望的。
使用gdb进行的初步跟踪表明,进行计数的计数器对象的对象“cnt”具有不同的地址。我想这是管道中的某种复制吗?如果是这样,如何过滤“计数器”有什么用?

最佳答案

查看the documentation,您可以使用以下任一方法:

#include <iostream>
#include <boost/iostreams/filtering_stream.hpp>
#include <boost/iostreams/device/null.hpp>
#include <boost/iostreams/filter/counter.hpp>
namespace io = boost::iostreams;
int main()
{
    io::counter cnt;
    io::filtering_ostream out(cnt | io::null_sink());
    out << "hello";
    std::cout << out.component<io::counter>(0)->lines() << " " << out.component<io::counter>(0)->characters() << std::endl;
}

要么:
#include <iostream>
#include <boost/iostreams/filtering_stream.hpp>
#include <boost/iostreams/device/null.hpp>
#include <boost/iostreams/filter/counter.hpp>
#include <boost/ref.hpp>
namespace io = boost::iostreams;
int main()
{
    io::counter cnt;
    io::filtering_ostream out;
    out.push(boost::ref(cnt));
    out.push(io::null_sink());
    out << "hello";
    std::cout << cnt.lines() << " " << cnt.characters() << std::endl;
}

08-06 13:29