我刚刚发现下面的代码不是一个有效的C++(它不在~
之后的int
处解析):
int x = 5;
x.~int();
但是,以下代码段确实有效:
int32_t x = 5;
x.~int32_t();
这是因为 int32_t
在我的特定 C++ 实现中是一个 typedef
,显然可以在任何 typedef 的类型上调用析构函数。
我的问题是:是否需要任何 C++ 实现才能允许第二个片段进行编译?特别是,int32_t
是否保证是 typedef,如果编译器知道 typedef typedef 将某些内容转换为 int,是否需要允许销毁 typedef?
最佳答案
明确要求 int32_t
是 typedef。我们从 [cstdint.syn]/2 开始:
The header defines all functions, types, and macros the same as 7.18 in the C standard.
所以从那里我们看一下 C 库的需求:
The typedef name intN_t designates a signed integer type with width N, no padding bits, and a two’s complement representation.
[强调添加]
所以是的,int32_t
必须是“typedef 名称”。
尽管(据我所知)它从未在规范文本中直接说明,但以下注释清楚地表明,为解析为内置类型的 typedef 调用析构函数旨在编译并成功( [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();
关于c++ - 在 int32_t 上调用析构函数是否合法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34424726/