假设我有一个类foo
具有函数 release
调用 delete this
:
struct foo
{
std::int32_t release() const
{
delete this;
return 0;
}
};
为什么我可以打电话
delete this
假设该函数为const
?返回 0 时的行为是否已定义?
delete
之后的函数不是“sort-of-die”吗? ?
引用标准的答案(这样我可以在我的代码中添加奇特的注释)将不胜感激。
最佳答案
- 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 ]
和
- Is the behaviour on returning 0 defined?
我认为这是安全的。 delete this;
将调用析构函数并释放对象(包括成员变量和基类子对象)所占用的内存。之后,如果您不取消引用 this
或访问任何成员变量,那么它将是安全的。
关于c++ - 函数中 `delete this` 的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33119348/