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。
如果 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> 的虛保護成員函式) |
[虛] |
返回輸入序列中下一個可用的字元 (虛保護成員函式) |