c++ - 伪析构函数调用不会破坏对象

标签 c++ language-lawyer destructor primitive-types explicit-destructor-call

考虑以下代码:

#include <iostream>

typedef int t;
t a=42;

int main()
{
    a.t::~t();
    std::cout << a; //42
}

我预计 a 将被销毁。但事实并非如此,为什么?那个伪析构函数调用是如何销毁对象的?

最佳答案

But it is not true, why?

§5.2.4/1:

The only effect is the evaluation of the postfix-expression before the dot or arrow.

其中 postfix-expression 是发生调用的对象的表达式。因此,伪析构函数调用,作为对普通析构函数的调用,不会结束它所应用的对象的生命周期。例如,

int i = 0;
(i += 5).~decltype(i)();
std::cout << i;

实际上你不能为标量调用析构函数,因为它们没有析构函数(参见 [class.dtor])。该语句仅允许用于模板代码,在模板代码中您调用了您不知道其类型的对象的析构函数 - 它消除了为标量类型编写专门化的必要性。


评论中指出,[expr.pseudo] 确实暗示存在标量的析构函数

The use of a pseudo-destructor-name after a dot . or arrow -> operator represents the destructor for the non-class type named by type-name.

但是,这与标准的其他部分不一致,例如§12,将析构函数称为特殊成员函数并提到

A destructor is used to destroy objects of its class type.

这似乎是在 C++98 days 中造成的不精确。

关于c++ - 伪析构函数调用不会破坏对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24000710/

相关文章:

memory-management - 这是 `std::mem::drop` 的有效实现吗?

c++ - 忽略 clang-tidy 中的系统头文件

c++ - 使用 hash_map 时,在 STL 字符串上使用的最佳散列算法是什么?

c# - C# 是否需要 private 关键字?

c - 返回语句后的序列点?

c++ - 静态成员变量的构造函数和析构函数(指针)

c++ - 如何在不改变原始颜色的情况下使用着色器

c++ - 删除默认 C++ 复制和移动构造函数以及赋值运算符的缺点?

c++ - 是否必须初始化成员才能获取其地址?

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