class Base{
virtual void sth() =0;
virtual void destroy_me(){}
};
class Derived : public Base{
void sth(){}
void destroy_me(){
delete this;
}
};
Is this safe behavior if I am absolutely sure that Derived
was dynamically allocated? I don't want to use a destructor as some derived classes in my design are not supposed to destroy themselves while others are, e.g.
class Safe : public Base{
void sth(){};
void destroy_me(){return;}
}
Classes of type Safe
are supposed to be deallocated the 'proper' way by calling delete
.
EDIT: To give more info why I am doing this. I have a binary tree structure of the type
class Node{
private:
Node* lhs;
Node* rhs;
public:
Base* compute(); // recursive
};
The idea is that I am using Derived
for some temporary computations while Safe
is an object stored in a proper data structure. If compute()
returns a pointer to Derived
I would like to delete it while if it returns a pointer to Safe
, I want to keep the object as it will always be stored in another data structure that I properly deallocate at the end of the program.