簡體   English   中英

C ++中的新建,刪除和子類

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

TextItemXObject的子類。

我試圖弄清楚為什么以下工作:

  TextItem *textItem = new TextItem();
  XObject *xItem = textItem;
  delete textItem;

但這不是:

  TextItem *textItem = new TextItem();
  XObject *xItem = textItem;
  delete xItem;

第二個示例在delete失敗,並帶有斷言失敗( _BLOCK_TYPE_IS_VALID )。

XObject *xItem = textItem;
delete xItem;

僅當 XObject具有虛擬析構函數時,此方法才有效 否則, delete語句將調用未定義的行為。

class XObject
{
    public:
       virtual ~XObject();
     //^^^^^^ this makes virtual destructor
};

確保XObject具有virtual析構函數,或者您的第二個片段具有未定義的行為

struct XObject
{
    // now deleting derived classes
    // through this base class is okay
    virtual ~XObject() {}
};

struct TextItem : XObject {};

XObject是否不提供虛擬析構函數? 如果沒有虛擬析構函數,則通過基本指針刪除TextItem時會出現不確定的行為。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM