1
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.

niko
  • 1,128
  • 1
  • 11
  • 25
  • Only if you're 100% sure that you are not, in fact, in a derived class of `Derived`. – Brian Bi Mar 23 '16 at 21:46
  • For context, could you elaborate on the thinking behind *"some derived classes in my design are not supposed to destroy themselves while others are"*? – NPE Mar 23 '16 at 21:48
  • You must actually have a destructor because `delete this;` will invoke it. But the destructor can be protected or private. Also, if you intend to call this on classes derived from Derived, then Derived must have a virtual destructor. (Probably `Base` should too). – M.M Mar 23 '16 at 21:52
  • NPE, check the edited question – niko Mar 23 '16 at 21:53
  • 2
    With your edit, if you have a pointer to `Base` and you call `object->destroy_me()`, how will you know if you need to also call `delete`? – Kevin Mar 23 '16 at 21:54
  • 2
    So if you have a `Base*` then you don't know whether you're supposed to destroy it with `delete` or with `destroy_me`? Sounds like a bad design to me. – Brian Bi Mar 23 '16 at 21:54
  • I added one more edit to clarify on my design – niko Mar 23 '16 at 22:10
  • 2
    Possible duplicate of [C++: Delete this?](http://stackoverflow.com/questions/3150942/c-delete-this) – PiotrNycz Mar 23 '16 at 22:27

0 Answers0