std::basic_stringbuf<CharT,Traits,Allocator>:: overflow
|
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++标准。
| 缺陷报告 | 适用范围 | 发布时的行为 | 正确行为 |
|---|---|---|---|
| LWG 169 | C++98 | 分配的缓冲区仅能容纳一个额外字符 | 允许容纳更多额外字符 |
| LWG 432 | C++98 |
overflow
将
epptr()
移动到恰好超过新写入位置
(当
std::stringbuf
以输入模式打开时)
|
不移动该指针 |
参见
|
[virtual]
|
将字符从放置区写入到关联的输出序列
(
std::basic_streambuf<CharT,Traits>
的虚受保护成员函数)
|
|
[virtual]
|
返回输入序列中的下一个可用字符
(虚受保护成员函数) |