When to use “delete”?

前端 未结 5 1724
天命终不由人
天命终不由人 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:20

    Think about what happens:

    In your loop you create a new instance of Obj and assign some values to it. This instance is created on your heap - thus you have to free it afterwards. When you add the instance to the vector you implicitely create a copy of it - because you have a vector of objects, not of pointers. Thus the vector keeps its own copy of Obj. You are safe to delete your Obj instance.

    BTW:

    • you could even reuse the object instance and create and free it outside of your loop
    • it's not necessary to allocate the Obj instance on the heap

    Obj x; x.u =i; x.v = i+1; objList.push_back(x);

    would also do

    You should read some articles about smart pointers and smart pointer containers. Eg. boost::scoped_ptr, boost::shared_ptr, std::auto_ptr. Using these paradigms there's usually no need to call delete by yourself.

提交回复
热议问题