c++ - 在 int32_t 上调用析构函数是否合法?

标签 c++ destructor

我刚刚发现下面的代码不是一个有效的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/

相关文章:

c++ - 读取字符串 C++ 的字符时出错

c++ - 在 C++ 中使用 auto 声明变量有缺点吗?

c# - 在 C# 中编码(marshal) C++ wchar_t**

c++ - 在RAII结构中修改RVO值是否安全?

c++ - 在析构函数中调用 remove() 删除文件是否安全?

c++ - 我认为我没有正确销毁动态内存

c++ - glEnable(GL_TEXTURE_GEN_S) GL_INVALID_OPERATION

c++ - 我将如何构建 Box2D 以在 Code::Blocks/Mingw32(Windows) 中工作

c++ - 在 C++ 中强制最后破坏某些东西

c++ - 如果调用了子类的析构函数,是否可以停止调用其基类的析构函数?