释放抽象类指针
在C++中,我有一个类A
,它有一个抽象类指针,以允许类B
中包含多态性,我有另一个指向抽象类C<的指针/code> 将
B 类
的子类的具体实例分配到该内存中,我需要从 C 类
调用清理(参见下面的问题)函数来取消分配class 的子类占用的内存B
我从堆中分配的,问题是我不能保证我可以访问清理函数,因为我只有一个指向 class C
的指针,我不能复制它,因为当我调用需要销毁包含的类A
时它可能已经消失了。
为了解决无法访问清理函数的问题,即使我指向子类,我是否可以在class A
指针上调用delete? C++ new 是否也像 malloc 一样存储堆块大小,以便您可以删除由指向这样的抽象类的指针引用的内存?如果没有,是否有另一种方法来组织允许我处理的程序情况如何?
In C++ I have a class A
that has an abstract class pointer to allow for polymorphism contained in a class B
, I have another pointer to an abstract class C
that allocates a concrete instance of a child class of class B
into that memory and I need to call a cleanup (see question below) function from class C
to deallocate the memory taken by the child class of class B
that I allocated from the heap, the problem is I can't guarantee I have access to the cleanup function because I only have a pointer to class C
which I can't just copy, because it could be gone by the time I call need to destroy the containing class A
.
In order to solve the problem of not having access to the cleanup function can I call delete on the class A
pointer even though I'm pointing to a child class? Does C++ new also store heap block size like malloc so that you can just delete memory referenced by a pointer to an abstract class like this? If not is there another way to organize the program that allows me to handle the situation?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我正在使用我的水晶球,因为很难理解你的问题,但你可能需要虚拟析构函数。
I'm using my crystal ball because it's hard to follow your question but you probably need virtual destructors.
该标准规定(§5.3.5 ¶3):
如果我理解正确的话,您有一个某种派生类型的对象,并且持有一个指向它的指针,其静态类型是其基类之一;所以,只要你有虚拟析构函数,就可以了。
编辑好吧,我太慢了:P
The standard states (§5.3.5 ¶3):
If I understood correctly, you have an object of some derived type, and you hold a pointer to it whose static type is one of its base classes; so, you're ok, as far as you have
virtual
destructors.Edit well, I was way too slow :P