Built-in type destructors (int, char, etc.)

In C ++, the following code gives a compiler error:

void destruct1 (int * item) { item->~int(); } 

This code is almost the same, I just type int on a different type and something magical happens:

 typedef int myint; void destruct2 (myint * item) { item->~myint(); } 

Why does the second code work? Does int get the destructor just because it was typed?

In case you are wondering why it would ever be desirable to do this: it comes from refactoring C ++ code. We remove the standard heap and replace it with homemade pools. This requires a challenge from us - a new one and destructors. I know that calling destructors for primitive types is useless, but we want them to be in the code if we later replace the POD with real classes.

Finding out that the bare int does not work, but the typed commands were a surprise.

Btw - I have a solution that includes boilerplate functions. We just print inside the template, and everything is fine.

+52
c ++ constructor destructor typedef
Jan 19 '09 at 1:43
source share
1 answer

This is the reason your code works for general parameters. Consider container C:

 template<typename T> struct C { // ... ~C() { for(size_t i = 0; i<elements; i++) buffer[i].~T(); } }; 

It would be frustrating to introduce special cases for built-in types. Thus, C ++ allows you to do the above even if T turns out to be equal to int . The holy standard says in 12.4 p15 :

The designation for explicitly calling the destructor can be used for any scalar type name. This allows you to write code without knowing if a destructor exists for this type.

The difference between using a simple int and typedef'ed int is that they are syntactically different. The rule is that in a call to the destructor, the thing after ~ is the type name. int not such a thing, but typedef-name. See it in 7.1.5.2 .

+76
Jan 19 '09 at 2:05
source share



All Articles