使用 C++ 中的成员函数删除对象

Deleting objects using a member function in C++

本文关键字:函数 删除 对象 成员 C++ 使用      更新时间:2023-10-16

有这个:

class Foo
{
public:
    void destroy() { delete this; }
public:
    // Stuff here...
};
int main(int argc, char *argv[])
{
    Foo* foo = new Foo;
    // Option 1
    delete foo;
    // Option 2:
    foo->destroy();
    return 0;
}
选项

1 和选项 2 是同一操作吗?这是摧毁物体的"正确"方法吗?为什么/为什么不呢?

非常感谢

是的,在这种情况下,两者是等效的。

但是您绝对应该更喜欢选项 1。 delete this很容易出错,违反了各种设计原则,在这种情况下是完全没有意义的。

这种销毁方案(删除this指针的成员函数)是实现仅允许堆上的实例的类时的常见解决方案

class Foo
{
    ~Foo(); // private destructor - won't allow objects on the stack
public:
    void destroy() { delete this; }
public:
    // Stuff here...
};

在上面的例子中,析构函数不能被调用,所以你不能说

delete FooInstance;

避免内存泄漏的唯一选择是具有destroy功能:

FooInstance->destroy();

除此之外,我还没有发现任何现实世界中/必须使用这种破坏功能的情况。

正如其他人所说,这并不常见和气馁。一个通常可靠的消息来源说,如果你严格遵守一些规则,你可以在技术上做到这一点;特别是,不要在删除:http://www.parashift.com/c++-faq/delete-this.html 后访问释放的内存或类成员。

选项 1 是删除类对象的推荐方法。

class Foo
{
public:
    ~Foo()
    {
       //define destructor if you have any pointer in your class
    }
public:
    // Stuff here...
};

int main()
{
    Foo* foo = new Foo;
    // By deleting foo it will call its destructor 
    delete foo;
}

对于选项 2

C++常见问题精简版有一个专门针对此的条目http://www.parashift.com/c++-faq-lite/freestore-mgmt.html#faq-16.15

只要你小心,对象自杀是可以的(删除这个)。