考虑以下代码:
#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/