Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it legal to call a destructor on int32_t?

Tags:

c++

destructor

I just found out that the following code is not a valid C++ (it doesn't parse at int after ~):

int x = 5;
x.~int();

However, the following snippet does work:

int32_t x = 5;
x.~int32_t();

This is because int32_t is a typedef in my particular implementation of C++, and a destructor can, apparently, be called on any typedef'ed type.

My question is: is any implementation of C++ required to allow the second snipped to compile? In particular, is int32_t guaranteed to be a typedef, and is the compiler required to allow a destruction of a typedef if it knows that typedef typedefs something to int?

like image 338
Ishamael Avatar asked Dec 22 '15 21:12

Ishamael


People also ask

Do destructors need to be called?

No. You never need to explicitly call a destructor (except with placement new ). A class's destructor (whether or not you explicitly define one) automagically invokes the destructors for member objects. They are destroyed in the reverse order they appear within the declaration for the class.

How do you call a destructor in C++?

Use the obj. ~ClassName() Notation to Explicitly Call a Destructor Function. Destructors are special functions that get executed when an object goes out of scope automatically or is deleted by an explicit call by the user.

Does C automatically call destructors?

A default-destructor is created automatically by the compiler if you do not define one yourself.

How do you make sure a destructor is called?

the destructor is called when code is execused to line "finish". If the object is created via a pointer(for example,A * a2 = new A();),the destructor is called when the pointer is deleted(delete a2;).


1 Answers

There's a clear requirement that int32_t be a typedef. We start with [cstdint.syn]/2:

The header defines all functions, types, and macros the same as 7.18 in the C standard.

So from there we look at the requirement for the C library:

The typedef name intN_t designates a signed integer type with width N, no padding bits, and a two’s complement representation.

[emphasis added]

So yes, int32_t must be a "typedef name".

Although (as far as I know) it's never stated directly in normative text, the following note makes it clear that invoking a destructor for a typedef that resolves to a built-in type is intended to compile and succeed ( [class.dtor]/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();
like image 174
Jerry Coffin Avatar answered Oct 28 '22 22:10

Jerry Coffin