New, delete, and subclasses in C++
TextItem
is a subclass of 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
).
XObject *xItem = textItem;
delete xItem;
This would work only if XObject
has virtual destructor. Otherwise, the delete
statement invokes undefined behavior.
class XObject
{
public:
virtual ~XObject();
//^^^^^^ this makes virtual destructor
};
Make sure that XObject
has a virtual
destructor, or your second snippet has undefined behavior:
struct XObject
{
// now deleting derived classes
// through this base class is okay
virtual ~XObject() {}
};
struct TextItem : XObject {};
Does XObject
not provide a virtual destructor? When you don't have a virtual destructor, you will get undefined behaviour when deleting the TextItem
through a base pointer.
精彩评论