C++基类子类的析构函数

基类的析构函数不为虚函数

class Base {
public:
    Base(int a = 0) {
        cout << "Base default constructor" << endl;
        p = new int(a);
    }
    ~Base() {
        cout << "Base destructor" << endl;
        if (nullptr != p) {
            delete p;
            p = nullptr;
        }
    }
private:
    int *p;
};
class Inherit : public Base {
public:
    Inherit(int b = 0) {
        cout << "Inherit default constructor" << endl;
        q = new int(b);
    }
    ~Inherit() {
        cout << "Inherit destructor" << endl;
        if (nullptr != q) {
            delete q;
            q = nullptr;
        }
    }
private:
    int *q;
};

基类对派生类及对象不需要进行操作时。

int main(void)
{
    Base *b = new Base(2);
    delete b;
    b = nullptr;
    return 0;
}


  这时不能定义虚函数,因为这样会增加内存开销。当类里面有定义虚函数时,编译器会给类增加一个虚函数表,里面来存放虚函数指针,这样就增加了类的存储空间。只有当一个类被用来作为基类的时候,才把析构函数写成虚函数。

示例

int main(void)
{
    Base *b = new Inherit(3);
    delete b;
    b = nullptr;
    return 0;
}

C++基类子类的析构函数_第1张图片
  会发现,当基类的析构函数不为虚函数时,当基类对象操控派生类对象以及对象时,当程序结束时会发现,派生类的析构没有调用,存在潜在的内存泄漏问题。

你可能感兴趣的:(C/C++)