Prashant Mishra
Prashant Mishra

Reputation: 177

can i apply delete on this pointer inside a member function?

As I understand if the member function has been called using pointer to an object which is allocated dynamically, the object would get delete. But if the member function has been called using the object, which is allocated statically, then what will happen ?

class sample
{
    int i;
  public:
    void func()
    {
        delete this;
    }
};

void main()
{
    sample *s = new sample;

    s->fun();
    sample s1;
    s1.fun();
}

Upvotes: 1

Views: 440

Answers (3)

Steve
Steve

Reputation: 1810

You can only use delete if the object was allocated using new. Simple as that. Therefore the first example you gave is legal, the second is not. The second case is likely to crash, or worse, cause heap corruption and crash at a seemingly random memory allocation somewhere far removed from the problem.

Upvotes: 2

mystic_coder
mystic_coder

Reputation: 472

If you call delete this inside any member function of object which is statically allocated , then calling delete this will crash at runtime . Because when this object will go out of scope , compiler will automatically call destructor , which will try to delete object which no longer exists.

Upvotes: -1

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726609

Deleting a pointer inside a member function is OK, as long as you know how that pointer has been allocated. There is no portable way of knowing that from just a pointer alone.

If a function is passed a pointer that has not been allocated dynamically, and the function calls delete on that pointer, it is undefined behavior. Moreover, even pointers to dynamic objects allocated as arrays cannot be freed with the regular delete operator: you must use delete[] on them. A simple rule is that when you do not know the origin of a pointer, you do not call delete on it.

Upvotes: 3

Related Questions