c++ - 函数中 `delete this` 的行为

标签 c++

假设我有一个类foo具有函数 release调用 delete this :

struct foo
{
    std::int32_t release() const
    {
        delete this;
        return 0;
    }
};
  1. 为什么我可以打电话delete this假设该函数为const

  2. 返回 0 时的行为是否已定义? delete 之后的函数不是“sort-of-die”吗? ?

引用标准的答案(这样我可以在我的代码中添加奇特的注释)将不胜感激。

最佳答案

  1. Why can I even call delete this given that the function is const?

从标准中,5.3.5$2 删除[expr.delete]

[ Note: a pointer to a const type can be the operand of a delete-expression; it is not necessary to cast away the constness (5.2.11) of the pointer expression before it is used as the operand of the delete-expression. —end note ]

  1. Is the behaviour on returning 0 defined?

我认为这是安全的。 delete this; 将调用析构函数并释放对象(包括成员变量和基类子对象)所占用的内存。之后,如果您不取消引用 this 或访问任何成员变量,那么它将是安全的。

关于c++ - 函数中 `delete this` 的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33119348/

相关文章:

c++ - boost::program_options 缓冲区溢出

c++ - 如何检测作为参数传递的函数的参数类型?

c++ - 可以使用ofstream在打印机上打印

c++ - 反转 for 循环...想要反向打印数字

c++ - 从子类调用基类

c++ - 保存命令行参数并对其进行类型转换

c++ - 带空的算术运算?

co_await 表达式中的 c++ coroutines temporaries

c++ - 在函数中切换case语句不会切换C++

c++ - vector 的成对迭代