开发者

Deleting object from a stack

Is it bad/illegal C++ to delete manually objects from a sta开发者_如何学Cck 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?


You are only allowed to delete those objects that have been allocated with new. If you try to call delete on a pointer pointing to an object on the stack, you will probably crash your program.


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.


There is one corner case, which I can think of, where it is OK to delete the local object manually.

struct A{
    A(){}
    int x;
    ~A(){}
};

int main(){
    char buf[sizeof(A)];
    A *p = new(buf)A();
    p->~A();
}


Usually you will have a method which allows you to edit the stack and usually the actual stack isn't exposed to the outside world to be manipulated outside the accessors defined on the class. So I'd say it is bad because there could be other properties and state inside the object representing the stack that become unsynced when you remove items manually.


If you need to know that ownership is transferred, then don't use raw pointers. Use smart pointers, such as std::auto_ptr (Boost and C++0x have many more) which make the transfer of ownership explicit and additionally convey how to destroy the objects (for auto_ptr this means delete):

struct Example {
  Example(std::auto_ptr<T> parent, std::auto_ptr<TObject> left,
          std::auto_ptr<T> right)
  : _parent (parent), _left (left), _right (right)
  {}

private:
  std::auto_ptr<T> _parent, _left, _right;
};

You could still store raw pointers, if you really insist, by using auto_ptr's release method and writing a copy ctor, destructor, and assignment operator for Example (the Rule of Three).


Use references instead of pointers.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜