Topic: delete this and class derivation
Author: tony@online.tmx.com.au (Tony Cook)
Date: 1995/08/31 Raw View
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();
}
And the following:
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();
}
Note that (AFAIK) the first case would be equivalent to the second
if an implementation used an object layout where the base object was
not at the start of the derived object.
--
Tony Cook - tony@online.tmx.com.au
100237.3425@compuserve.com
---
[ 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. ]
Author: ajay@lehman.com (Ajay Kamdar)
Date: 1995/08/31 Raw View
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. ]