C++ streambuf::pubsync() 函式



C++ 的std::streambuf::pubsync()函式用於將緩衝區與相關的輸入/輸出序列同步。通常,此函式呼叫受保護的虛擬函式sync(),該函式處理實際的同步。

如果sync()成功,則返回0,否則返回-1。

語法

以下是std::streambuf::pubsync()函式的語法。

int pubsync();

引數

它不接受任何引數。

返回值

它返回streambuf中sync的預設定義,始終返回零,表示成功。

異常

如果丟擲異常,則流緩衝區處於有效狀態。

資料競爭

它修改流緩衝區物件。

示例1

在下面的示例中,我們將考慮pubsync()函式的基本用法。

#include <iostream>
#include <streambuf>
#include <sstream>
int main() {
   std::stringstream a;
   a << "Hello";
   std::streambuf * b = a.rdbuf();
   int result = b -> pubsync();
   std::cout << "Result : " << result << std::endl;
   return 0;
}

輸出

以上程式碼的輸出如下:

Result : 0

示例2

考慮下面的示例,我們將執行多次插入後的同步。

#include <iostream>
#include <sstream>
int main() {
   std::ostringstream x;
   x << "A ";
   x << "B ";
   x << "C ";
   int result = x.rdbuf() -> pubsync();
   std::cout << "Result: " << result << std::endl;
   std::cout << "Buffer content: " << x.str() << std::endl;
   return 0;
}

輸出

以上程式碼的輸出如下:

Result: 0
Buffer content: A B C

示例3

讓我們看一下下面的示例,我們將檢查std::cin上的pubsync()。

#include <iostream>
int main() {
   std::streambuf * pbuf = std::cin.rdbuf();
   int a = pbuf -> pubsync();
   std::cout << "Result : " << a << std::endl;
   return 0;
}

輸出

如果我們執行以上程式碼,它將生成以下輸出:

Result : 0
streambuf.htm
廣告