[英]Does it make sense to add final keyword to the virtual function in a class that has no base class (is not derived)
[英]Sanity check: Does returning !EOF from streambuf-derived class' overflow function make sense?
关于重写的 std::streambuf::overflow function 应该如何简单地获取写入 stream 的每个字符,我几乎找不到有用的信息。所以我向 ChatGPT 询问了一些指示。 它不断回到这个概念:
int overflow(int c)
{
if (c == EOF)
{
// Flush the buffer here
return !EOF;
}
// Put c in the buffer here
if (c == '\n')
{
// Flush the buffer here
}
return c;
}
当 c 是EOF
时,它返回!EOF
真是太奇怪了。
文档没有详细说明“成功”的含义。
This page说它应该返回EOF
(不是!EOF
)当以EOF
作为参数调用时(或发出“失败”信号时)。
所以:我怀疑在这里返回!EOF
是错误的并且我应该返回EOF
是否正确?
如果您能告诉我 ChatGPT 从哪里得到这个想法,请使用 Cookie 点数。 我找不到return;EOF;
inte.net 上的任何其他地方。
这是 C++ 标准对返回值的描述:
[streambuf.virt.put]
int_type overflow(int_type c = traits::eof());
6返回:
traits::eof()
或如果 function 失败则抛出异常。
否则,返回traits::eof()
以外的一些值以指示成功。(304)(脚注 304)通常,
overflow
返回c
以指示成功,除非traits::eq_int_type(c, traits::eof())
返回true
,在这种情况下它返回traits::not_eof(c)
。
因此,具体的返回值并不重要,重要的是它是否为traits::eof()
。 您可能想要遵循一个(非规范的)约定。
回复:“成功”是什么意思:
[streambuf.virt.put]/5要求:此虚拟 function 的每个覆盖定义都应遵守以下约束:
...
- 令
r
为待处理序列中未消耗的字符数。 如果r
为非零值,则应设置 pbase(pbase()
和pptr()
以便:pptr() - pbase() == r
并且从 pbasepbase()
开始的r
字符是关联的 output stream。如果r
全部为零(待处理序列的字符已被消耗)然后将pbase()
设置为nullptr
,或者 pbase(pbase()
和pptr()
都设置为相同的非空值。- 如果向关联的 output stream 附加一些字符失败,或者无法根据上述规则建立 pbase(
pbase()
和pptr()
,则 function 可能会失败。
因此,如果 function 无法实际写入底层介质,或者无法恢复不变量,则会失败。 如果它管理两者,它就会成功。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.