2

私は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'とは異なるアドレスを持っていることを示しています。パイプラインでのコピーのようなものだと思いますか?その場合、フィルター「カウンター」はどのように役立ちますか?

4

1 に答える 1

1

ドキュメントを見ると、次のいずれかを使用できます。

#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;
}
于 2012-11-23T08:07:56.303 に答える