有没有一种简单的方法可以检查 STL::ostream 中是否序列化了某些内容。我正在寻找类似的东西:
some preparation
// ... a very complex code that may result in adding or not to the stream,
// that I will prefer not to change
check if the stream has something added
请注意,这需要递归地工作。使用 register_callback 是个好主意还是有更简单的方法?
最佳答案
首先是直接的问题:register_callback()
旨在处理存储在 pword()
中的资源的适当复制和释放,并且将只进行与此相关的操作(即,复制、分配和释放加上观察 std::locale
变化)。所以,不,那对你一点帮助都没有。
然而,您可以做的是创建一个过滤流缓冲区,它观察是否有对流的写入,例如,像这样:
class changedbuf: std::streambuf {
std::streambuf* d_sbuf;
bool d_changed;
int_type overflow(int_type c) {
if (!traits_type::eq_int_type(c, traits_type::eof())) {
this->d_changed = true;
}
return this->d_sbuf->sputc(c);
}
public:
changedbuf(std::streambuf* sbuf): d_sbuf(d_sbuf), d_changed() {}
bool changed() const { return this->d_changed; }
}
您可以使用它来代替您已有的 std::ostream
,例如:
void f(std::ostream& out) {
changedbuf changedbuf(out.rdbuf());
std::ostream changedout(&changedbuf);
// use changedout instead of out; if you need to use a global objects, you'd
// replace/restore the used stream buffer using the version of rdbuf() taking
// an argument
if (changedbuf.change()) {
std::cout << "there was a change\n";
}
}
真正的实现实际上会提供一个缓冲区并处理适当的刷新(即覆盖 sync()
)和序列输出(即覆盖 xsputn()
)。但是,上述版本足以作为概念验证。
其他人可能会建议使用 std::ostringstream
。根据写入的数据量,这很容易成为性能消耗者,尤其是与适当处理缓冲的 changedbuf
的高级版本相比。
关于c++ - 检查是否在 std::ostream 中序列化了某些内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17892675/