Placement new and templates

K

Kalle Rutanen

Hello.

The following code compiles fine with VC7. I seemingly call int's
destructor. Why does it compile ? What does the standard say about this
?

#include <new>

using namespace std;

template <typename T>
void destruct(T* that)
{
that->~T();
}

int main()
{
char memory[100];
int* a = 0;

// Can do this...
a = new(memory) int;
destruct(a);

// But can't do this
a = new(memory) int;
//a->~int();

return 0;
}
 
V

Victor Bazarov

Kalle said:
The following code compiles fine with VC7. I seemingly call int's
destructor. Why does it compile ? What does the standard say about
this ?


It's explicitly allowed. It's called "pseudo-destructor call". The
Standard defines that in 5.2.4. If your compiler does not allow you
do

int *pa;
...
pa->~int();

then your compiler is broken. For built-in types a pseudo-destructor
call has no effect except to evaluate the expression before the . or
the ->.

V
 
M

msalters

Victor Bazarov wrote:
If your compiler does not allow you
do

int *pa;
...
pa->~int();

then your compiler is broken. For built-in types a pseudo-destructor
call has no effect except to evaluate the expression before the . or
the ->.

So a pedantic compiler may reject this as UB, considering
that you're dereferencing an uinitialized pointer ;)

Of course, normal compilers will just skip this instruction.

Regards,
Michiel Salters
 
V

Victor Bazarov

msalters said:
Victor Bazarov wrote:
If your compiler does not allow you



So a pedantic compiler may reject this as UB, considering
that you're dereferencing an uinitialized pointer ;)

The '...' contains all the necessary code to prevent the UB.

V
 
K

Kalle Rutanen

It's explicitly allowed. It's called "pseudo-destructor call". The
Standard defines that in 5.2.4. If your compiler does not allow you
do

int *pa;
...
pa->~int();

then your compiler is broken. For built-in types a pseudo-destructor
call has no effect except to evaluate the expression before the . or
the ->.

Thank you for a clearing 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

Similar Threads

templates?? 2
Placement new[] 5
placement new overhead 12
Variadic templates std::tuple 2
templates 10
Templates and g++ 4
Overriding placement new correctly 1
Operator overloading with templates 5

Members online

No members online now.

Forum statistics

Threads
473,982
Messages
2,570,186
Members
46,740
Latest member
JudsonFrie

Latest Threads

Top