gpt4 book ai didi

c++ - 当你有一个虚拟析构函数时,基类指针中的 "delete this"会删除派生类对象吗?

转载 作者:太空狗 更新时间:2023-10-29 23:46:03 25 4
gpt4 key购买 nike

我有一个三层深的类层次结构,如下所示:

class A {
public:
virtual ~A() {}

}

class B : public A {
public:
virtual ~B() {}
void foo(E *e) {
e->remove(this);
}
}

class C : public B {
public:
~C() {}
}

class E {
public:
void remove(A *a) {
delete a;
}
}

好的,所以我想知道当我在 C 的对象上调用 foo() 时会发生什么。它是要删除整个对象还是只删除对象的 BA 部分,而将 C 部分留在内存中?

最佳答案

Is it going to remove the entire object or only the B and A part of the object, and leave the C part still in memory?

没有。它将“做正确的事情”(即删除最派生的子对象,运行其所有析构函数等)提供 A (即,指针的指针对象的静态类型 delete) 有一个虚拟析构函数(如果类 A 有一个虚拟析构函数,它的所有后代也有它)。这也适用于多重继承。

关于c++ - 当你有一个虚拟析构函数时,基类指针中的 "delete this"会删除派生类对象吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14183057/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com