簡體   English   中英

C++ 標准是否保證當“rdbuf”的返回值傳遞給流輸出運算符時,緩沖區的內容被打印出來

[英]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_istreamstd::basic_ostream以及從它們派生的所有對象( std::ofstreamstd::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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM