Class A
{
public:
NullIt()
{
this = NULL;
}
Foo()
{
NullIt();
}
}
A * a = new A;
a->Foo();
assert(a); //should assert here
Run Code Online (Sandbox Code Playgroud)
有没有办法实现这种效果,内存泄漏?
不.对象对外部引用一无所知(在本例中为"a"),因此无法更改它们.
如果您希望调用者忘记您的对象,那么您可以这样做:
class MyClass
{
void Release(MyClass **ppObject)
{
assert(*pObject == this); // Ensure the pointer passed in points at us
*ppObject = NULL; // Clear the caller's pointer
}
}
MyClass *pA = new A;
pA->Release(&pA);
assert(pA); // This assert will fire, as pA is now NULL
Run Code Online (Sandbox Code Playgroud)
当你调用Release时,你将你持有的指针传递给对象,并将其NULL化,这样在调用之后,你的指针就是NULL.
(Release()也可以"删除这个;"以便它同时破坏自己)