Mo Sanei
Mo Sanei

Reputation: 475

How to delete the current class instance using a member function of the same class

In the following code, I made my constructor and destructor private and created my own instantiation and deletion functions. But when I call the Delete() function, the delete this statement inside it seems to remove the object but not notify the compiler so it thinks the object still exists. I thought it would be a good idea to set the pointer to null or zero so I put a this = 0 before the delete statement but it didn't work at all. What should I put inside the Delete() function in order to completely delete the object and its pointer?

class MyClass
{
private:
  MyClass() {}
 ~MyClass() {}
public:
  static MyClass *Instantiate()
  {
    MyClass *inst = new MyClass;
    return inst;
  }
  void Delete()
  {
    delete this;
  }
};

int main()
{
  MyClass *inst1 = MyClass::Instantiate();
  inst1->Delete();
  return 0;
}

Upvotes: 1

Views: 5841

Answers (2)

Nikos C.
Nikos C.

Reputation: 51840

You cannot do this. Pointers to the object need to be managed externally, as the object itself does not have access to them (this is a local, self-referencing pointer and does not represent anything else than that.)

If you wanted to keep track of the pointers automatically, you would use a smart pointer class (http://en.wikipedia.org/wiki/Smart_pointer#C.2B.2B_smart_pointers). But since you made the dtor private, you lose that ability. You can still write your own smart pointer class, of course.

Upvotes: 2

Although you didn't explicitly express it, I believe you're wondering why inst1 is not NULL after invoking Delete(). If so, consider this:

With inst1->Delete(); you successfully delete the object inst1 pointed to. However, the pointer inst1 remains unchanged. It only points somewhere in memory that is no longer a valid instance of MyClass.

Also it is extremely uncommon for a member function to call delete this, though syntactically and semantically there's nothing wrong with your example.

Upvotes: 3

Related Questions