可能重复:
C++:删除这个?
面向对象的自杀或删除此;
我想知道下面的代码是否安全运行:
#include <iostream>
using namespace std;
class A
{
public:
A() {
cout << "Constructor" << endl;
}
~A() {
cout << "Destructor" << endl;
}
void deleteMe() {
delete this;
cout << "I was deleted" << endl;
}
};
int main()
{
A *a = new A();
a->deleteMe();
cout << "Exit ...";
return 0;
}
Run Code Online (Sandbox Code Playgroud)
输出是:
Constructor
Destructor
I was deleted
Exit ...
Run Code Online (Sandbox Code Playgroud)
并且程序正常退出,但这里有一些内存访问暴力吗?
如果delete this在该调用之后没有人将使用该对象,则可以.如果对象在堆上分配,当然
例如,cocos2d-x游戏引擎就是这样做的.它使用相同的内存管理方案Objective-C,这里是一个基础对象的方法:
void CCObject::release(void)
{
CCAssert(m_uReference > 0, "reference count should greater than 0");
--m_uReference;
if (m_uReference == 0)
{
delete this;
}
}
Run Code Online (Sandbox Code Playgroud)
我不认为这是一种c++管理记忆的方式,但它是可能的