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

My Status, Ciphertext 2
Where is my virtual function??? 12
Blue J Ciphertext Program 2
Virtual function call optimization 10
Inheritance machanism 2
Infinite loop problem 1
Non virtual and inheritance 7
Placement new[] 5

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,007
Latest member
obedient dusk

Latest Threads

Top