What I want to do is overload the delete operator for my class to automatically set the pointer to null after deleting it so I can safe delete it inside a member function, like that:
# include <iostream>
class Buddy
{
public:
Buddy(void) : _hp(100) { }
~Buddy(void) { std::cout << "Buddy is dead!" << std::endl; }
void operator delete(void * ptr)
{
::delete (Buddy*)ptr;
ptr = nullptr;
}
void getDamage(int amount)
{
_hp -= amount;
if (_hp <= 0)
delete this;
}
private:
int _hp;
};
void hitBuddy(Buddy *buddy)
{
if (!buddy)
std::cout << "Buddy is already dead!" << std::endl;
else
{
std::cout << "Hitting buddy!" << std::endl;
buddy->getDamage(70);
}
}
int main(void)
{
Buddy *dude = new Buddy;
hitBuddy(dude);
hitBuddy(dude);
hitBuddy(dude);
return (0);
}
But it doesn't set the pointer to null and it calls two times the destructor, is there a proper way to set the pointer to null inside the class like I want to do? (OUTPUT)
Hitting buddy!
Hitting buddy!
Buddy is dead!
Buddy is dead!
Hitting buddy!
Buddy is dead!
Buddy is dead!
a.out(79480,0x10d3cbdc0) malloc: *** error for object 0x7fe345c05790: pointer being freed was not allocated
a.out(79480,0x10d3cbdc0) malloc: *** set a breakpoint in malloc_error_break to debug
[1] 79480 abort ./a.out