Self terminate
I have the following code:
class A {
public:
void Terminate();
A * pSelf;
A();
}
A::A()
{
this->pSelf = this;
}
void
A::Terminate ()
{
delete this->pSelf;
}
A * pObj = new A;
pObj->Terminate();
Will it work? or will it be problematic?
well, i hope you'll be far away when it will explode (-:
just imagine you need an array of objects A
just imagine you need an array of objects A
That'll work fine, as long as after you delete an object you don't attempt to access any member variables, call member functions that access member variables, or call any virtual member functions.
It should work fine, although you don't actually need to store a pSelf value. Just use this. A common example of deleting this is in reference-counted classes:
[edit]...I am slow...[/edit]
class c_RefCounted{ public: c_RefCounted() : mRefCount(1) {} void Attach(); void Detach(); private: ~c_RefCounted() {} unsigned long mRefCount;};void c_RefCounted::Attach(){ ++mRefCount;}void c_RefCounted::Detach(){ --mRefCount; if (mRefCount == 0) delete this;}
[edit]...I am slow...[/edit]
just remember that delete[] must be used when alocated with new[], and delete when alocated with new.
Quote:Original post by Agony
It should work fine, although you don't actually need to store a pSelf value. Just use this. A common example of deleting this is in reference-counted classes:
*** Source Snippet Removed ***
[edit]...I am slow...[/edit]
As you can see from Agony example, if your going to do such things make the destructor private otherwise you may end-up calling delete twice then bang.
As others have said, delete this; is legit, but dangerous outside of a tightly controlled environment. And yeah, if you're planning on deriving from that class, you'd better make your destructor virtual, otherwise you're in deep doo-doo.
If your outside code is going to call foo->Terminate(), it might as well just call delete foo.
If your outside code is going to call foo->Terminate(), it might as well just call delete foo.
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement