[英]New, delete, and subclasses in C++
TextItem
is a subclass of XObject
. TextItem
是XObject
的子类。
I am trying to figure out why the following works: 我试图弄清楚为什么以下工作:
TextItem *textItem = new TextItem();
XObject *xItem = textItem;
delete textItem;
But this does not: 但这不是:
TextItem *textItem = new TextItem();
XObject *xItem = textItem;
delete xItem;
The second example fails on delete
, with an assertion failure ( _BLOCK_TYPE_IS_VALID
). 第二个示例在
delete
失败,并带有断言失败( _BLOCK_TYPE_IS_VALID
)。
XObject *xItem = textItem;
delete xItem;
This would work only if XObject
has virtual destructor. 仅当
XObject
具有虚拟析构函数时,此方法才有效 。 Otherwise, the delete
statement invokes undefined behavior. 否则,
delete
语句将调用未定义的行为。
class XObject
{
public:
virtual ~XObject();
//^^^^^^ this makes virtual destructor
};
Make sure that XObject
has a virtual
destructor, or your second snippet has undefined behavior : 确保
XObject
具有virtual
析构函数,或者您的第二个片段具有未定义的行为 :
struct XObject
{
// now deleting derived classes
// through this base class is okay
virtual ~XObject() {}
};
struct TextItem : XObject {};
Does XObject
not provide a virtual destructor? XObject
是否不提供虚拟析构函数? When you don't have a virtual destructor, you will get undefined behaviour when deleting the TextItem
through a base pointer. 如果没有虚拟析构函数,则通过基本指针删除
TextItem
时会出现不确定的行为。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.