开发者

Crashed when i delete a c++ object [duplicate]

开发者 https://www.devze.com 2023-01-24 20:12 出处:网络
This question already has answers here: Closed 12 years ago. Possible Duplicate: When to use virtual destructors?
This question already has answers here: Closed 12 years ago.

Possible Duplicate:

When to use virtual destructors?


[Second dicuss] hi,guys! You are all talking about virtual-destructor. And also i think about the base class`s destructor. But another test as this: class A { public: A() { } 开发者_运维技巧 virtual void fun() { } private: int mIntA; };

when class A have a vitual function(not virtual-destrcutor), it`s ok. Deleting ptrA is OK!

So, i think A just need a vptr to activate the polymorphic. Not class As destructor must be virtual. Class As destructor being not virtual just can make resources is not released correctly.


class A
{
 public:
  A()
  {
  }
  /*virtual*/ ~A()
  {
  }
 private:
  int mIntA;
};

class B : public A
{
public:
 B()
 {
  mIntB = 1234;
 }

 virtual ~B()
 {
  int i = 0;
 }

private:
 int mIntB;
};

I have a class A. And a class B derived form A; A doesn`t have any virtual function. so when i do this:

A* ptrA = new B;
delete ptrA;

it crashes!

but when add a virtual fun to A. it`s ok. as we know, ptrA is a B object. but why is it?


The A class isn't polymorphic, therefore the delete has no possibility to know that ptrA actually points inside an allocated block and therefore the deallocation crashes.


You have a non-virtual destructor!

(which means that when the destructor is called, it's A's destructor that is called, rather than B's, even though the object was allocated as a B)

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号