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()
不同,典型的 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++ 标准。
缺陷报告 | 应用于 | 发布时的行为 | 正确的行为 |
---|---|---|---|
LWG 169 | C++98 | (重新)分配的缓冲区只能多容纳一个字符 | 允许更多额外字符 |
LWG 432 | C++98 | 若 std::stringbuf 为输入打开,则 overflow 曾移动 epptr() 指向新的写位置之后不再移动它 |
it is not moved |
[编辑] 参阅
[虚] |
从放置区向关联输出序列写入字符 ( std::basic_streambuf<CharT,Traits> 的虚保护成员函数) |
[虚] |
返回输入序列中下一个可用的字符 (虚保护成员函数) |