C++ faq-lite 11.10 placement new object destruction

F

Fei Liu

The faq states that an explicit call to the destructor must be made,
however, I don't see why a simple 'delete f' wouldn't work in this case.
At least my test code works correctly on FC5 with g++ 4.1.1. 'delete
f' correctly invokes 'f->~Fred()' and 'operator delete'.

void someCode()
{
char memory[sizeof(Fred)];
void* p = memory;
Fred* f = new(p) Fred();
...
f->~Fred(); // Explicitly call the destructor for the placed object
}

any comments?

Fei
 
V

Victor Bazarov

Fei said:
The faq states that an explicit call to the destructor must be made,
however, I don't see why a simple 'delete f' wouldn't work in this
case. At least my test code works correctly on FC5 with g++ 4.1.1.
'delete f' correctly invokes 'f->~Fred()' and 'operator delete'.

void someCode()
{
char memory[sizeof(Fred)];
void* p = memory;
Fred* f = new(p) Fred();
...
f->~Fred(); // Explicitly call the destructor for the placed
object }

any comments?

The actual memory for 'memory' is not allacated using 'new' or 'new[]',
so calling 'delete' (or 'delete[]') for it has undefined behaviour.

V
 
F

Fei Liu

Victor said:
Fei said:
The faq states that an explicit call to the destructor must be made,
however, I don't see why a simple 'delete f' wouldn't work in this
case. At least my test code works correctly on FC5 with g++ 4.1.1.
'delete f' correctly invokes 'f->~Fred()' and 'operator delete'.

void someCode()
{
char memory[sizeof(Fred)];
void* p = memory;
Fred* f = new(p) Fred();
...
f->~Fred(); // Explicitly call the destructor for the placed
object }

any comments?

The actual memory for 'memory' is not allacated using 'new' or 'new[]',
so calling 'delete' (or 'delete[]') for it has undefined behaviour.

The behavior is not undefined if Fred also provides 'operator delete'
that does not actually free any memory. The Faq needs to clarify on this
point instead of a plain statement that an explicit call to the
destructor must be made.

Fei
 
R

Roland Pibinger

Victor said:
The actual memory for 'memory' is not allacated using 'new' or 'new[]',
so calling 'delete' (or 'delete[]') for it has undefined behaviour.

The behavior is not undefined if Fred also provides 'operator delete'
that does not actually free any memory.

That "Fred also provides 'operator delete'" is not obvious from your
posted code. Moreover, I'm not sure that your assertion is backed by
the C++ Standard.
The Faq needs to clarify on this
point instead of a plain statement that an explicit call to the
destructor must be made.

Probably not (see Victor Bazarov's answer)
 

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

Members online

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,053
Latest member
BrodieSola

Latest Threads

Top