延长了C++中临时对象的使用寿命

extending the life of temporary objects in C++

本文关键字:临时对象 C++      更新时间:2023-10-16

我正在读到:http://herbsutter.com/2008/01/01/gotw-88-a-candidate-for-the-most-important-const/

// Example 3
Derived factory(); // construct a Derived object
void g() {
  const Base& b = factory(); // calls Derived::Derived here
  // … use b …
} // calls Derived::~Derived directly here — not Base::~Base + virtual dispatch!

我理解第一个和第二个例子,但我不理解第三个例子。特别是,什么是lreference/reference,什么是"病毒调度"。这个例子太好了。

如果您编写如下代码:

void g() {
  Base* b = new Derived; // calls Derived::Derived here
  // … use b …
  delete b;
}

因为b的类型是Base *,所以如果基析构函数是虚拟的,因为virtual dispatch,派生析构函数将被调用,因为基指针指向的对象具有派生的类型。

相反,如果你使用

void g() {
  Derived* d = new Derived; // calls Derived::Derived here
  // … use d …
  delete d;
}

无论基析构函数是否为虚拟析构函数,都会调用派生析构函数。不需要虚拟调度。

作者想强调的是,在示例3中,甚至如果基析构函数不是虚拟的,则会调用派生析构函数。因为没有调用析构函数,因为引用超出了范围,但因为基引用不再需要(派生类型的)临时对象。(必须是常量)