When to use “delete”?

前端 未结 5 1720
天命终不由人
天命终不由人 2020-12-06 07:36

I want to store 10 Obj object in objList, but i don\'t know when is appropriate use delete in this case. If i use delete Obj;

5条回答
  •  半阙折子戏
    2020-12-06 08:15

    You wanna use the heap, so I suggest changing your vector declaration to vector of pointers, something like this.

    vectorobjList;
    

    Why? Because if it is a vector of Obj's, then the things you're storing are actually copies of the value Obj of the pointers you created. objList's items and the obj pointers you create are totally separated and unrelated! So when you,

    delete obj
    

    The things on objList are totally completely unaffected in any ways.
    Moreover, vector (no asterisk), stores its item as Obj and they are on the stack, they will disappear when your program goes out of scope!

提交回复
热议问题