4

Possible Duplicate:
Destructors of builtin types (int, char etc..)

Template Function:

template<typename T> void kill(T* type)
{
    type->~T();
}

Call:

int x= 5;
kill(&x);

woah, it compiled!? How can a primitive type like int have a destructor? It is also working with char , bool etc.

Community
  • 1
  • 1
ApprenticeHacker
  • 21,351
  • 27
  • 103
  • 153

2 Answers2

4

§12.4.16 of the Standard says

16 [ Note: the notation for explicit call of a destructor can be used for any scalar type name (5.2.4). Allowing this makes it possible to write code without having to know if a destructor exists for a given type. For example,

typedef int I;
I* p;
p->I::~I();

—end note ]

Seth Carnegie
  • 73,875
  • 22
  • 181
  • 249
  • so the compiler ignores any call to the destructor of a scalar type? – ApprenticeHacker Jan 24 '12 at 06:01
  • @IntermediateHacker whether it specially ignores them or just sees that they do nothing and leaves them out of the code, the effect is the same. It's a feature probably specifically meant for making it easier to write templates (though I can only guess; I don't know if this feature was there before C++ had templates). Also btw, your code exhibits undefined behaviour because the integer is destructed twice :) – Seth Carnegie Jan 24 '12 at 06:03
  • @SethCarnegie: There is no undefined behavior due to multiple pseudo-destructor calls. The only effect will be evaluation of expression before `.` or `->`. Moreover, there seems to be no UB for multiple calls of trivial destructors for the same object. – Konstantin Oznobihin Jan 24 '12 at 06:24
1

The relevant part of the standard is §5.2.4/1:

The use of a pseudo-destructor-name after a dot . or arrow -> operator represents the destructor for the non-class type named by type-name. The result shall only be used as the operand for the function call operator (), and the result of such a call has type void. The only effect is the evaluation of the postfix expression before the dot or arrow.

Jerry Coffin
  • 476,176
  • 80
  • 629
  • 1,111