🚀 go-pugleaf

RetroBBS NetNews Server

Inspired by RockSolid Light RIP Retro Guy

Article View: comp.std.c++
Article #1874

Re: delete this and class derivation

#1874
From: 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. ]
Technical Details
Message-ID: <MATT.95Aug31111350@physics10.Berkeley.EDU>
Path: arc1-ca.pugleaf.net!128.32.155.1!matt

Show Full Headers
Complete Article Headers
Path: arc1-ca.pugleaf.net!128.32.155.1!matt
From: ajay@lehman.com (Ajay Kamdar)
Newsgroups: comp.std.c++
Subject: Re: delete this and class derivation
Date: 31 Aug 1995 18:13:50 GMT
Organization: <none>
Approved: matt@physics10.Berkeley.EDU (Matt Austern)
Message-ID: <MATT.95Aug31111350@physics10.Berkeley.EDU>
NNTP-Posting-Host: physics10.berkeley.edu