user8584996
user8584996

Reputation:

Will deleting a pointer to an object in the destructor of a certain class automatically delete it from the heap?

Everytime I was coding a game, I always utilized this piece of code for the destructor:

A::~A()
{
    delete this;
}

Will this actually delete an object on the heap when the scope for it is over?

Upvotes: 0

Views: 83

Answers (1)

Hatted Rooster
Hatted Rooster

Reputation: 36463

Doing this makes no sense as the destructor is called upon deletion of the object ( delete invokes the destructor), there's no reason to call delete again. In the best case scenario where the object you are freeing is actually allocated by new you are doing a double delete on your object. In the other case you are calling delete on an object not created by new. Both are undefined behavior.

Upvotes: 8

Related Questions