c++ - boost::iostreams::counter 似乎不起作用

标签 c++ boost iostream

我在玩 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;
}

关于c++ - boost::iostreams::counter 似乎不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13524960/

相关文章:

C++ 复杂类的运算符 >> 中的不明确重载

c++ - 使用 cout 输出 cerr

c++ - 如何在for循环中包含两个索引值测试条件?

c++ - 使用 gmock 保存 C 样式数组值

python - 如何在Python中编译、创建共享库以及导入c++ boost模块

c++ - 在同一个类/结构中具有相同签名的相同函数?重载?

c++ - 输出流作为类成员

c++ - 函数中作为引用的指针地址

c++ - 使用 std::mutex 复制类

c++ - 如何在 XCode 中正确包含 Boost 文件(C++ 第三方库)?