延长了C++中临时对象的使用寿命
extending the life of temporary objects in C++
我正在读到: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中,甚至如果基析构函数不是虚拟的,则会调用派生析构函数。因为没有调用析构函数,因为引用超出了范围,但因为基引用不再需要(派生类型的)临时对象。(必须是常量)
相关文章:
- 在不复制临时对象的情况下延长其生存期
- 为什么当我们有常量引用时创建临时对象?
- 程序如何'remember'临时对象?
- 返回对临时对象的引用
- 防止临时对象文件访问 MSVC 中的磁盘
- 是否可以在C++中移动临时对象的属性?
- 通过引用传递临时对象
- 临时C++对象是否为左值?
- 临时对象:术语澄清
- 存储对(可能)临时对象的引用是否合法,只要引用不比对象存活?
- 临时对象有身份吗?
- 临时对象上的运算符重载
- 如何在没有 std::move 的情况下移动临时对象
- 临时对象在C++中是不可避免的吗?
- 编译错误:临时对象构造函数中缺少参数
- 为什么在按值返回时创建临时对象,而不是在按值传递给函数参数时创建临时对象
- 我试图创建临时对象的方式有错误吗
- 子表达式中临时对象的生存期
- 对临时对象的Const引用不会延长其生存期
- 为什么引用类型在使用临时对象访问时是左值