☰
  • 首页
  • 规则分类
  • 项目介绍
search
•••

禁用 delete this

14.21 ID_this_forbidDeleteThis
目录 › next › previous

使用 delete this 须保证:

  • 对象是用 new 创建的,但不能用 new[]
  • 使用 delete this 后,除非重新构造对象,否则不能再访问相关非静态成员
  • 不能在析构函数中使用 delete this

由于限制条件易被打破,对框架以及语言工具之外的业务类或算法类代码建议禁用 delete this。

示例:

class A {
    ....
public:
    void foo() {
        delete this;   // Non-compliant
    }
};

auto* p = new A;
p->foo();              // Looks innocent

p = new A[10];
p->foo();              // Memory is still leaking

如果有必要使用 delete this,应将类的析构函数设为非 public,使对象只能通过 new 创建,并确保执行 delete this 后 this 指针再也不会被访问,而且不能用 new[] 创建数组,否则仍然存在内存泄漏等问题。

参考

CWE-1082
Copyright©2024 360 Security Technology Inc., Licensed under the Apache-2.0 license.