使用 C++ 中的成员函数删除对象
Deleting objects using a member function in C++
有这个:
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
只要你小心,对象自杀是可以的(删除这个)。
相关文章:
- 如何通过 getter 函数删除矢量的元素?
- C++类析构函数删除成员(如果"owner"?
- 使用私有析构函数删除动态分配的对象
- C ++(为什么)确实移动构造函数删除运算符=
- 析构函数删除错误的元素
- C++ 类析构函数删除部分但不是全部成员数据
- 如何使用 deleteEntry 函数 c++ 删除数组中的单个字符串
- 仅仅以避免隐式复制构造函数删除,使用shared_ptr而不是unique_ptr作为类成员明智
- 析构函数删除在 main 中声明的动态数组
- 如果未分配申报表,是否需要删除或处理动态数组?还是它被函数删除
- C++ 函数删除一行
- g++空函数删除是否递归工作
- C++析构函数删除东西(对象,指针?)太快
- C++析构函数删除包含动态数组作为数据成员的对象时的用法
- C++11 析构函数 = 删除
- 父类析构函数删除具有外部启动元素的子类
- 函数删除太多
- C++析构函数删除共享内存
- C++,如何让此函数删除存储在数组中的字符串
- 析构函数删除数组时出错