C++ std::destroy(T * pointer)

c++, stl

Solution

Note that, while `a->~int();` doesn't compile, this does:

typedef int INT;
int* a;
a->~INT();

From the standard:

5.2.4p1 The use of a `pseudo-destructor-name` after a dot . or arrow -> operator represents the destructor for the non-class type denoted by `type-name` or `decltype-specifier`. 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.

From 5.2p1:

pseudo-destructor-name:
  nested-name-specifier_opt type-name :: ~ type-name
  nested-name-specifier template simple-template-id :: ~ type-name
  nested-name-specifier_opt~ type-name
  ~ decltype-specifier

And finally, 7.1.6.2p1:

type-name:
  class-name
  enum-name
  typedef-name
  simple-template-id

So, curiously, `int` is not syntactically a `type-name` (it's a `simple-type-specifier`) and so you can't call `~int()`, but `INT` is and so you can.

Problem

The STL code I am reading may be old...but the question is more related to C++ template grammar. The question surrounds this stl template function: ``` template<class T> std::destroy(T *p) { p->~T(); } ``` I can't seem to find a specialization of the std::destroy(T *) function. So it seems to me that the template function will instantiate same for "int" types, and invoke "int"'s destructor. To make my point, I created this sample code that emulate the std::destroy. I call it my_destroy ih the example. ``` #include <iostream> #include <stdio.h> using namespace std; template <class T> void my_destroy(T * pointer) { pointer->~T(); } int main() { int *a; //a->~int(); // !!! This won't compile. my_destroy<int>(a); // !!! This compiles and runs. } ``` } To my surprise, this line doesn't compile: ``` a->~int(); ``` But this line compiles: ``` my_destroy<int>(a); ``` My confusion is, I thought that `my_destroy<int>(a)` will be instantiated as the equivalent of `a->~int();` To a question in larger context, when a STL container of `<int>` erases an element, how does the `std::destroy()` work?

Original source