![](/img/trans.png)
[英]Error during copying stream in c++ using the rdbuf() and operator <<
[英]Does the C++ standard guarantee that when the return value of 'rdbuf' passed to the stream output operator, he conent of the buffer gets printed out
考慮以下代碼片段:
std::stringstream ss;
ss << "hello world!\n";
auto a = ss.rdbuf();
std::cout << a; // prints out "hello world!
變量a
是指向std::stringbuf
類型對象的指針。 當它通過 GCC9.4 傳遞給流輸出運算符<<
時,將打印出a
指向的流緩沖區的內容。
我的問題是:這種行為只是在 GCC 中實現std::stringbuf
的方式造成的意外,還是語言標准保證這將始終有效?
std::basic_stringbuf
派生自std::basic_streambuf 。 Cppreference 描述了它的使用:
I/O 流對象
std::basic_istream
和std::basic_ostream
以及從它們派生的所有對象(std::ofstream
、std::stringstream
等)完全根據std::basic_streambuf
實現。
這意味着什么? 好吧,讓我們看一下std::basic_istream::operator<<
這里的重載集:
basic_ostream& operator<<( std::basic_streambuf<CharT, Traits>* sb );
(10)
表現為
UnformattedOutputFunction
。 在構造並檢查哨兵對象后,檢查sb
是否為空指針。 如果是,則執行setstate(badbit)
並退出。 否則,從sb
控制的輸入序列中提取字符並將它們插入到*this
中,直到滿足以下條件之一:
- 文件結束出現在輸入序列上;
- 在輸出序列中插入失敗(在這種情況下,不提取要插入的字符);
- 發生異常(在這種情況下捕獲異常)。
如果沒有插入字符,則執行
setstate(failbit)
。 如果在提取時引發異常,則設置failbit
,如果在exceptions()
中設置了failbit
,則重新引發異常。
所以,是的,標准保證std::cout << ss.rdbuf();
會有你觀察到的效果。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.