-1

为什么在这段代码中调用了 Derived 类的析构函数?

#include <iostream>

class Base
{
public:
   Base() { std::cout << "Base::Base() \n"; }
   ~Base() { std::cout << "Base::~Base() \n"; } 
};

class Derived : public Base
{
public:
   Derived() { std::cout << "Derived::Derived() \n"; }
   ~Derived() { std::cout << "Derived::~Derived() \n"; } 
};

Derived foo() { return Derived(); }

int main()
{
   const Derived& instance = foo();
}
4

2 回答 2

3

为什么在这段代码中调用了 Derived 类的析构函数?

因为在主程序结束时Derived创建的实例超出了范围。foo()

#include <iostream>
using namespace std;

class Base {
public:
    Base() {
        std::cout << "Base::Base() \n";
    }
    ~Base() {
        std::cout << "Base::~Base() \n";
    }
};

class Derived: public Base {
public:
    int i;
    Derived() {
        i = 10;
        std::cout << "Derived::Derived() \n";
    }
    ~Derived() {
        i = 0;
        std::cout << "Derived::~Derived() \n";
    }
    int get() {
        return i;
    }
};

Derived foo() {
    return Derived();
}

int main() {
    const Derived& instance = foo();
    cout << instance.i << endl;
    return 0;
}

输出如下:

Base::Base()
Derived::Derived()
10
Derived::~Derived()
Base::~Base()
于 2012-09-05T17:21:10.157 回答
3

为了使它更有趣,请考虑修改main

const Base& instance = foo();

该代码创建了一个临时类型(由 返回的对象foo),Derived并通过将其绑定到类型的常量引用来延长对象的生命周期Base。临时对象的生命周期将延长,直到引用超出范围,此时对象将被销毁。代码大致翻译为:

Derived __tmp = foo();
const Base& instance = __tmp;

在持有引用的块的末尾instance__tmp变量也超出范围并被删除。请注意,即使没有虚拟析构函数,也会调用适当的析构函数,就像__tmp类型Derived(函数返回的类型)一样。

于 2012-09-05T17:42:45.070 回答