c++ - 对具有重载运算符的类型进行就地销毁->

标签 c++ operator-overloading destructor forwarding

假设某些类型 Foo 有一个重载的 operator-> 返回一个 Bar*:

struct Foo
{
    Bar* operator->();
};

如果我想从 Foo 类中就地析构返回的 Bar 实例,我可以编写以下代码吗?

this->~Bar();

g++ 不喜欢那个代码。如果我这样写就可以了:

(*this)->~Bar();

“递归转发规则”在这种情况下不适用吗?为什么不呢?

最佳答案

这是链接 -> 的规则,可在标准的 13.5.6 [over.ref] 中找到:

An expression x->m is interpreted as (x.operator->())->m for a class object x of type T if T::operator->() exists and if the operator is selected as the best match function by the overload resolution mechanism (13.3).

因为 this 是一个指针,而不是一个类对象,所以它不适用。

相反,5.2.5 ([expr.ref]) 中的这条规则适用:

For the second option (arrow) the first expression shall have pointer to complete class type. The expression E1->E2 is converted to the equivalent form (*(E1)).E2; the remainder of 5.2.5 will address only the first option (dot).

关于c++ - 对具有重载运算符的类型进行就地销毁->,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6996600/

相关文章:

c++ - 禁止在 clang 前端查找预编译头文件

c++ - Opencv:如何获取然后更改 "Mat vector"的值

c++ - 如何在 C++ 中同时重载 = 和 [] 运算符

python - 在 python 中重载 [] 运算符?

c++ - 在派生类的析构函数中抛出异常

c++ - 父持有指向子数据成员的指针并在析构函数中使用数据成员函数

C++ 重载提取运算符 - 错误无法访问类中声明的私有(private)成员

c++ - 用模板实现虚函数的覆盖机制

c++ - 模板运算符重载函数上的 undefined symbol

c++ - 析构函数的 AVL 树内存问题