🚀 go-pugleaf

RetroBBS NetNews Server

Inspired by RockSolid Light RIP Retro Guy

1 total messages Started by Ajay Kamdar Thu, 31 Aug 1995 18:13
Re: delete this and class derivation
#1874
Author: Ajay Kamdar
Date: Thu, 31 Aug 1995 18:13
73 lines
2101 bytes
In article <DE5J6J.69B@online.tmx.com.au>,
Tony Cook <tony@online.tmx.com.au> wrote:
>Is the following meant to be legal?
>
>class B
>{
>  public:
>    virtual ~B() { }
>    void f() { delete this; }
>};
>class D : public B
>{
>    int JustSomeData;
>};
>int main()
>{
>    D*d = new D;
>
>    d->f();
>}


Yes the use of delete in this example is legal.
The delete operator destroys a complete object. [5.3.5] Even though the
static type of the delete operand in f() is pointer to B, the expression
is legal because the B has a virtual destructor. The destructor of D will
be called correctly [12.4.9] and the pointer to D will be passed to a
memory deallocation function. Also [from 12.5.10] the deallocation
function actually called is determined by the destructor actually called.

>class B1
>{
>  public:
>    int JustSomeData;
>};
>class B2
>{
>  public:
>    virtual ~B2() { }
>    void f() { delete this; } // this might not point at start of D
>};
>class D : public B1, public B2
>{
>};
>int main()
>{
>    D *d = new D;
>    d->f();
>}


This is legal too. The same analysis as above applies to this case also.

However, if the above code fragment were to be changed to:
    D  *d  = new D;
    B1 *b1 = d;
    delete b1;

This will now yield undefined behavior because B1 does not have a virtual
destructor.




-- 
Ajay Kamdar                               Email: ajay@lehman.com   
Lehman Brothers                           Phone: (201) 524-5048 

---
[ comp.std.c++ is moderated.  Submission address: std-c++@ncar.ucar.edu.
  Contact address: std-c++-request@ncar.ucar.edu.  The moderation policy
  is summarized in http://dogbert.lbl.gov/~matt/std-c++/policy.html. ]
Thread Navigation

This is a paginated view of messages in the thread with full content displayed inline.

Messages are displayed in chronological order, with the original post highlighted in green.

Use pagination controls to navigate through all messages in large threads.

Back to All Threads