std::basic_stringbuf<CharT,Traits,Allocator>::overflow
来自 cppreference.cn
< cpp | io | basic stringbuf
protected: virtual int_type overflow( int_type c = Traits::eof() ); |
||
将字符 c 追加到输出字符序列。
如果 c 是文件结束指示符 (traits::eq_int_type(c, traits::eof()) == true),则没有字符要追加。该函数不执行任何操作,并返回一个未指定的值,但不是 traits::eof()。
否则,如果输出序列有可用的写入位置,或者此函数可以成功地创建一个可用的写入位置,则调用 sputc(c) 并返回 c。
如果 std::stringbuf 以输出模式打开 ((mode & ios_base::out) != 0),则此函数可以创建一个可用的写入位置:在这种情况下,它会重新分配(或初始分配)缓冲区,使其足够大以容纳整个当前缓冲区,外加至少一个字符。如果 std::stringbuf 也以输入模式打开 ((mode & ios_base::in) != 0),则 overflow
还会通过移动 egptr() 使其指向新写入位置之后的位置来增加读取区域的大小。
内容 |
[编辑] 参数
c | - | 要存储在放置区域的字符 |
[编辑] 返回值
Traits::eof() 表示失败,如果字符 c 成功追加,则返回 c,或者如果使用 Traits::eof() 作为参数调用,则返回 Traits::eof() 之外的某个值。
[编辑] 注释
此函数与典型的 overflow()
不同,后者会将缓冲区的内容移动到关联的字符序列,因为对于 std::basic_stringbuf,缓冲区和关联的序列是同一个。
[编辑] 示例
在用于执行此示例的实现 (例如 GCC-4.9) 中,overflow()
将放置区域过度分配为 512 字节:调用 str() 只会返回四个初始化的字节,但接下来 508 次对 sputc() 的调用不需要新的 overflow()
调用。
运行此代码
#include <sstream> #include <iostream> struct mybuf : std::stringbuf { mybuf(const std::string& new_str, std::ios_base::openmode which = std::ios_base::in | std::ios_base::out) : std::stringbuf(new_str, which) {} int_type overflow(int_type c = EOF) override { std::cout << "stringbuf::overflow('" << char(c) << "') called\n" << "Before: size of get area: " << egptr() - eback() << '\n' << " size of put area: " << epptr() - pbase() << '\n'; int_type ret = std::stringbuf::overflow(c); std::cout << "After : size of get area: " << egptr() - eback() << '\n' << " size of put area: " << epptr() - pbase() << '\n'; return ret; } }; int main() { std::cout << "read-write stream:\n"; mybuf sbuf(" "); // read-write stream std::iostream stream(&sbuf); stream << 1234; std::cout << sbuf.str() << '\n'; std::cout << "\nread-only stream:\n"; mybuf ro_buf(" ", std::ios_base::in); // read-only stream std::iostream ro_stream(&ro_buf); ro_stream << 1234; std::cout << "\nwrite-only stream:\n"; mybuf wr_buf(" ", std::ios_base::out); // write-only stream std::iostream wr_stream(&wr_buf); wr_stream << 1234; }
可能的输出
read-write stream: stringbuf::overflow('4') called Before: size of get area: 3 size of put area: 3 After : size of get area: 4 size of put area: 512 1234 read-only stream: stringbuf::overflow('1') called Before: size of get area: 3 size of put area: 0 After : size of get area: 3 size of put area: 0 write-only stream: stringbuf::overflow('4') called Before: size of get area: 0 size of put area: 3 After : size of get area: 0 size of put area: 512
[编辑] 缺陷报告
以下行为变更缺陷报告被追溯应用于先前发布的 C++ 标准。
DR | 应用于 | 已发布行为 | 正确行为 |
---|---|---|---|
LWG 169 | C++98 | (重新)分配的缓冲区只能容纳一个额外的字符 | 允许更多额外的字符 |
LWG 432 | C++98 | overflow 移动 epptr() 以指向新位置之后写入位置,如果 std::stringbuf 以输入模式打开 |
它不会被移动 |
[编辑] 参见
[虚函数] |
将字符从放置区域写入到关联的输出序列 (std::basic_streambuf<CharT,Traits> 的虚保护成员函数) |
[虚函数] |
返回输入序列中下一个可用的字符 (虚保护成员函数) |