简体   繁体   English

使用dynamic_cast转换它们后删除指针:分配的内存发生了什么

[英]Deleting pointers after casting them with dynamic_cast: what happenes to the allocated memory

Let's say we have the following class hierarcy: 假设我们有以下课程层级:

class B{     
    B() { cout<<"B\n"; }
    ~B(){ cout<<"~B\n"; }    
};

class D1 : virtual public B {
    D1() { cout<<"D1\n"; }
    ~D1(){ cout<<"~D1\n"; }
};

class D2 : virtual public B {
    D2() { cout<<"D2\n"; }
    ~D2(){ cout<<"~D2\n"; }
};

class MM : public D1, public D2 {
    MM() { cout<<"MM\n"; }
    ~MM(){ cout<<"~MM\n"; }
};

int main(){
    B *p = new MM();
    D1 *p2 = dynamic_cast<D1*>(p);
    D2 *p3 = dynamic_cast<D2*>(p);
    MM *p4 = dynamic_cast<MM*>(p);
    //delete p4;
    //delete p3;
    delete p2;
    delete p;
    return 0;
}

I'm not very used to dynamic_cast and pointers from base to derived classes so correct me if I'm wrong, but this basically creates a pointer of type B* to an object of type MM(). 我不习惯使用dynamic_cast和从基类到派生类的指针,所以如果我错了就纠正我,但这基本上会创建一个类型为B *的指针给MM()类型的对象。 After this it creates another two pointers, and uses dynamic_cast to cast the B* pointer to the D*, D2* and MM*. 在此之后它创建另外两个指针,并使用dynamic_cast将B *指针强制转换为D *,D2 *和MM *。

Now the thing that worries me is: the all four point to the same block of memory (right?). 现在让我担心的是:全部四个指向同一块内存(对吧?)。 And when we delete p2, and then p, it works OK. 当我们删除p2,然后删除p时,它可以正常工作。 The program crashes if we uncomment "delete p3" or delete "p4", and I've no idea why. 如果我们取消注释“删除p3”或删除“p4”,程序会崩溃,我不知道为什么。 I've alse observed that if we uncomment either of the previously mentioned delete statements and comment "delete p2" the code works fine. 我还注意到,如果我们取消注释前面提到的任何删除语句并注释“删除p2”,代码工作正常。

Could someone care to explain? 有人可以解释一下吗? Thank you! 谢谢!

PS: Would any of you be so kind as to also explain what happens to the allocated memory once we create another pointer and use cast the previous one with dynamic_cast? PS:你们中的任何一个人都会如此善良地解释一旦我们创建了另一个指针并使用前一个与dynamic_cast一起投射分配的内存会发生什么? Thanks! 谢谢!

Deleting class (without virtual destructor) via other type is undefined behaviour (UB). 通过其他类型删除类(没有虚拟析构函数)是未定义的行为(UB)。

Deleting pointer twice is also undefined behaviour (UB). 删除指针两次也是未定义的行为(UB)。

So your code may appear to work, but it is invalid too. 因此,您的代码似乎可以正常工作,但它也是无效的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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