Sign in to follow this  

Self terminate

This topic is 4861 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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?

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
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:

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]

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites

This topic is 4861 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this