std::basic_stringbuf<CharT,Traits,Allocator>::overflow
来自cppreference.com
< 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
。
若 stringbuf 为输出打开( mode & ios_base::out) != 0 ),则此函数能令写位置可用:此情况下,它重分配(或在最初分配)足够大的缓冲区,以保有整个当前缓冲区加上至少一个字符。若 stringbuf 亦为输入打开( (mode & ios_base::in) != 0 ),则 overflow
亦会通过移动 egptr() 到指向恰好越过新放置区的位置,来增加获取区的大小。
参数
c | - | 要存储于放置区的字符 |
返回值
若失败则为指示失败的 Traits::eof() 。若成功后附字符 c
则为 c
。或若以 Traits::eof() 为参数调用,则为某异于 Traits::eof() 的值。
注意
此函数异于典型的 overflow()
,后者移动缓冲区的内容到关联字符序列,因为 std::basic_stringbuf 的缓冲区和关联序列是同一序列。
示例
在用于执行此示例的实现中, 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(" "); // 只读流 std::iostream stream(&sbuf); stream << 1234; std::cout << sbuf.str() << '\n'; std::cout << "\nread-only stream:\n"; mybuf ro_buf(" ", std::ios_base::in); // 只读流 std::iostream ro_stream(&ro_buf); ro_stream << 1234; std::cout << "\nwrite-only stream:\n"; mybuf wr_buf(" ", std::ios_base::out); // 只写流 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
参阅
[虚] |
从放置区写入字符到关联的输出序列 ( std::basic_streambuf<CharT,Traits> 的虚受保护成员函数) |
[虚] |
返回输入序列中可用的下一字符 (虚受保护成员函数) |