std::endl 和 '\n' 之间的区别用于流缓冲区实现

发布于 2024-11-15 05:12:08 字数 706 浏览 5 评论 0原文

我目前正在尝试实现 stringbuf 的子类,以允许缓冲区标记特定字符(在我的例子中为“\n”),并在出现此字符时采取操作(将消息转储到记录器,然后在我的记录器中清除缓冲区)案件)。 为了实现这个目标,我覆盖了 sputc (以实现对 '\n' 的监视)和 xsputn (确实使用 sputc,因为 GCC 实现默认情况下似乎不这样做)。 出于调试目的,我让 sputc 将传递给它的每个字符写出到 stdout。

现在这是我的问题:如果我使用像

mystream << "Some text" << std::endl;

sputc 这样的东西接收除了 '\n' 之外的每个字符,该字符应该由 std::endl 引入,所以预期的操作不会完成,因为 '\n' 没有过去了。 如果我使用类似的东西

mystream << "Some text" << '\n';

,甚至

mystream << "Some text" << "\n" << std::flush;

一切都按预期工作,并且我的 sputc 实现得到 '\n' 字符。

所以我的问题是:两个代码行是否应该对后面的 stringbuf 执行完全相同的操作,如果不是,我必须重写哪些其他方法才能获取 '\n'?

I'm currently trying to implement a subclass of stringbuf to allow the buffer to tokenize for specific chars ('\n' in my case) and undertake an action if this char occurs (dump the message to a logger and clear buffer afterwards in my case).
To achieve this goal, I overrode sputc (to implement watching out for the '\n') and xsputn (to use sputc indeed, as the GCC implementation doesn't seem to do this by default).
For debugging purposes, I let sputc write out each character that is passed to it to stdout.

Now this is my question: If I use something like

mystream << "Some text" << std::endl;

sputc receives each character except of the '\n' which should be inducted by std::endl, so the action that is expected is not done because the '\n' isn't passed on.
If I use something like

mystream << "Some text" << '\n';

or even

mystream << "Some text" << "\n" << std::flush;

everything works as expected and my sputc implementation gets the '\n' char.

So my question is: Shouldn't both code lines do exactly the same concerning the stringbuf behind, and if not, which other methods do I have to override to get the '\n'?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

嗫嚅 2024-11-22 05:12:08

您无法覆盖 sputc,因为 sputc 不是虚拟的。您需要重载 overflowsync 并检查整个挂起序列中是否出现 \n

您实际上不需要重载 xsputn ,除非您可以做一些最佳的事情,因为您知道支持您的流类型的设备的一些特殊情况。

You can't override sputc because sputc is not virtual. You need to overload overflow and sync and examine the whole pending sequence for occurrences of \n.

You shouldn't really need to overload xsputn unless you can do something optimal because you know something special about the device that backs your stream type.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文