当调用析构函数时,此示例中使用了什么?

用户名

谁能告诉我析构函数在此代码中做什么?通话示例:“

int year = 2012; 
string hello = "Hello"; 
cout << format("% world! The year is %\n") << hello << year;

“我不知道使用“ while”来构造一个析构函数的想法……我们为什么需要它?这应该打印出来:“你好,世界!年份是2012年。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。

TempFormat format(const char*) { 
  return TempFormat(const char*); 
} 

class TempFormat { 
  const char* str; 
public: 
  TempFormat(const char* str) : str(str) {} 

  friend Format& operator<<(ostream& os, TempFormat& f) { 
    return Format(f.str, os); 
  } 
};

class Format {
  const char* str; 
  ostream& os; 
public: 
  Format(const char* str, ostream& os) : str(str), os(os) {} 

  template<class T> 
  Format& operator<<(const T& t) { 
    while(*str && *str != '%'){ 
      os << *str; 
      str++; 
    } 
    if (*str != '%') { 
      throw std::exception(); 
    } 
    os << t; 
    while(*str && *str != '%'){ 
      os << *str; 
      str++; 
    } 
    return *this; 
  } 

  ~Format() { 
    while(*str && *str != '%'){ 
      os << *str; 
      str++; 
    } 
    if (*str == '%') { 
      throw std::exception(); 
    } 
  } 
}; 
Medinoc

析构函数仅检查格式字符串中的所有“%”是否都已处理。如果字符串包含的“%”多于对象接收到的参数,则析构函数将引发异常。

编辑:该行cout << format("% world! The year is %\n") << hello << year;是非常弯曲的,因为<<这里运算符都不是经典ostream& operator<<(ostream&, type)重载。

  • 第一个<<实际上是Format& operator<<(ostream&, TempFormat&),它返回一个Format对象。这也是可憎的,它通过引用返回局部变量,并通过非恒定引用采用无名的临时变量。它甚至可以编译吗?它的原型可能应该Format operator<<(ostream&, TempFormat const&)改为。但是如果没有返回值优化(或一个好的move构造函数),它将抛出。
  • 第二个<<<实际上类型Format的插入运算符Format& Format::operator<<(const T&)string
  • 第三个'<<'实际上是带有类型Format的插入操作符Format& Format::operator<<(const T&)int

由于该Format对象是临时对象,因此在operator<<两次调用之后,该对象在行尾被销毁而且由于它只包含两个'%',因此它的析构函数不会抛出异常。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

为什么在使用unique_ptr时没有调用析构函数?

为什么在使用赋值时不调用析构函数的堆栈变量?

使用Vector创建对象时如何调用析构函数

在 Visual Studio 中使用指针时析构函数崩溃

为什么在此代码中调用了2次析构函数?

为什么要调用析构函数

为什么不调用析构函数?

在C ++中使用继承性调用析构函数的顺序是什么,销毁成员变量的顺序是什么?

为什么在此示例中未调用某些析构函数

是否在作业中调用了类析构函数?

C++ 析构函数调用了错误的对象?

析构函数调用

C ++为什么调用此析构函数,它从何而来

为什么在调用luaL_error时未调用C ++对象析构函数?

在 java 或 c++ 中使用“按名称调用”调用此函数的结果和示例是什么?

为对象分配值时为什么调用构造函数和析构函数

当对象绑定到成员函数时,为什么std :: function会调用析构函数?

如果调用了子类的析构函数,是否可以停止对其基类的析构函数的调用?

为什么类的构造函数被调用了四次,而在程序即将结束的时候,析构函数只被调用了两次?

什么时候在C ++中确切地调用了一个类的析构函数?

为什么此析构函数不必删除类对象?

当我单击控制台上的关闭按钮时,为什么不调用析构函数?

为什么在声明指向对象的指针时不调用析构函数

为什么在插入析构函数时总是得到“在抛出...实例后终止调用”?

在析构函数中引发异常时,为什么不调用重载的删除?

为什么在抛出我的析构函数时没有调用 std::terminate

为什么每次我迭代它们时都会调用向量中结构的析构函数?

析构函数调用抽象函数时会发生什么

为什么析构函数比构造函数调用得更多?