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?
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.
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.
A default-destructor is created automatically by the compiler if you do not define one yourself.
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;).
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With