gpt4 book ai didi

c++ - 类成员 `B` 的析构函数,为什么在下面的代码片段中调用它?

转载 作者:太空狗 更新时间:2023-10-29 19:43:22 24 4
gpt4 key购买 nike

从 §5.3.5[expr.delete]/1 中,我了解到对象 *a 的析构函数在下面的代码段中被调用。但是我不明白为什么在这种情况下调用了类成员 B 的析构函数,如 live example 中所示。 .

#include <iostream>
class A
{
public:
class B{ public: ~B(){ std::cout << "B dtor" << '\n'; } };
A() { p = new B(); }
operator B*() { return p; }
private:
B* p;
};

int main()
{
A* a = new A();
delete *a;
std::cout << "end" << '\n';
}

希望能从标准中引用一些解释这一点。

最佳答案

您的delete *a 将运算符delete 应用于类型非指针 表达式*a >一个。唯一合法的方法是类型 A 可以隐式转换为某种指针类型。

5.3.5 Delete [expr.delete]

1 ... The operand shall have a pointer to object type, or a class type having a single non-explicit conversion function (12.3.2) to a pointer to object type.

2 If the operand has a class type, the operand is converted to a pointer type by calling the above-mentioned conversion function, and the converted operand is used in place of the original operand for the remainder of this section.

在这种情况下,您的类 A 可以隐式转换为 B *,这正是您执行 delete *a 时发生的情况。

换句话说,你的delete *a实际上被解释为

delete (*a).operator B*();

您在代码中删除的是B,而不是A。这就是调用 B 的析构函数的原因。

如果你想销毁 A 对象,你必须这样做

delete a;

(注意,没有 *)。那不会调用 B 的析构函数。

关于c++ - 类成员 `B` 的析构函数,为什么在下面的代码片段中调用它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30764045/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com