简体   繁体   English

C ++中的新建,删除和子类

[英]New, delete, and subclasses in C++

TextItem is a subclass of XObject . TextItemXObject的子类。

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM