Virtual Placement Delete?

A

Andrew Tomazos

Please consider...

class B
{
virtual ~B() { ... }
}

class D : B
{
virtual ~D() { ... }
}

void f()
{
void* p = malloc(sizeof(D));
new (p) D; // ...placement new
B* b = (B*) p;
b->~B(); // ...is virtual destructor in effect?
free(p);
}

When f() is executed will D::~D() be called?

Thanks,
Andrew.
 
V

Victor Bazarov

Andrew said:
Please consider...

class B
{
public:

virtual ~B() { ... }
} ;

class D : B

Need public inheritance to convert:
class D : public B
{
virtual ~D() { ... }
} ;

void f()
{
void* p = malloc(sizeof(D));
new (p) D; // ...placement new
B* b = (B*) p;

That's *not* a good idea. You should do

D* pd = new (p) D; // ...placement new
B* b = pd;

instead.
b->~B(); // ...is virtual destructor in effect?
free(p);
}

When f() is executed will D::~D() be called?

With your current cast from 'p' to a B*, the behaviour is undefined I'm
afraid.

V
 
A

Andrew Tomazos

That's *not* a good idea.  You should do

      D* pd = new (p) D; // ...placement new
      B* b = pd;

instead.



With your current cast from 'p' to a B*, the behaviour is undefined I'm
afraid.

(1) Can you tell me what the difference is between:

new (p) D;
B* b = (B*) p;

and

D* pd = new (p) D;
B* b = pd;

I would have thought they were equivalent? Why aren't they?

(2) If I use your recommended form, will the virtual destructor of
D::~D be called if I call b->~B() ?

Thanks,
Andrew.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Members online

No members online now.

Forum statistics

Threads
474,265
Messages
2,571,069
Members
48,771
Latest member
ElysaD

Latest Threads

Top