Search code examples
c++delete-operator

Deleting object from a stack


Is it bad/illegal C++ to delete manually objects from a stack or there are situation when it is acceptable?

Edit

Constructor(pointer parent, pointer left, pointer right):parent_(parent),left_(left), right_(right)
{   }

   ~Constructor()
        {
        delete parent_;
        delete left_;
        delete right_;
        }


main()
{
Object parent;
Object left;
Object right;
Constructor c(&parent,&left,&right);
}

Is there any way to check if object is on heap or on stack?


Solution

  • Yes, it is bad to delete automatic variables (ie, objects on the stack). I suppose there is still no "never" in programming, but I can't think of a time/reason why you would want to do this.

    What scenario are you thinking of?

    EDIT: Actually, not only is it bad, it is illegal:

    5.3.5 Delete

    1: The delete-expression operator destroys a most derived object (1.8) or array created by a new-expression.