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
广告
© . All rights reserved.