C++ Istream 庫 - 保護塊 (sentry)



描述

它用於準備流進行輸入。所有執行輸入操作的成員函式都會自動構造此類的物件,然後對其進行評估(如果未設定任何狀態標誌,則返回 true)。只有當此物件評估結果為 true 時,函式才會嘗試執行輸入操作(否則,它會在不執行操作的情況下返回)。返回之前,函式會銷燬保護塊物件。

宣告

以下是 std::basic_istream::sentry 的宣告。

C++98

class sentry {
   public:
      explicit sentry (basic_istream& is, bool noskipws = false);
      ~sentry();
   operator bool() const;
   private:
      sentry (const sentry&);             
      sentry& operator= (const sentry&);  
};

C++11

class sentry {
   public:
      explicit sentry (basic_istream& is, bool noskipws = false);
      ~sentry();
      explicit operator bool() const;
      sentry (const sentry&) = delete;
      sentry& operator= (const sentry&) = delete;
};

成員

  • explicit sentry (basic_istream& is, bool noskipws = false); − 準備輸出流進行輸出操作,執行上述操作。

  • ~sentry(); − 不執行任何操作(實現定義)。

  • explicit operator bool() const; − 當評估物件時,它返回一個 bool 值,指示保護塊建構函式是否成功執行了所有任務:如果在構造過程的某個點設定了內部錯誤標誌,則此函式始終為此物件返回 false。

示例

下面的示例解釋了 std::basic_istream::sentry。

#include <iostream>
#include <string>
#include <sstream>
#include <locale>

struct Phone {
   std::string digits;
};

std::istream& operator>>(std::istream& is, Phone& tel) {
   std::istream::sentry s(is);
   if (s) while (is.good()) {
      char c = is.get();
      if (std::isspace(c,is.getloc())) break;
      if (std::isdigit(c,is.getloc())) tel.digits+=c;
   }
   return is;
}

int main () {
   std::stringstream parseme ("   (555)2326");
   Phone myphone;
   parseme >> myphone;
   std::cout << "digits parsed: " << myphone.digits << '\n';
   return 0;
}

讓我們編譯並執行上面的程式,這將產生以下結果:

digits parsed: 5552326
istream.htm
廣告