When to use “delete”?

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

    Any object you create on the heap with new needs to be cleared up by delete. In your code, you are actually storing a copy in your collection.

    objList.push_back(*Obj);
    

    What this line is doing step by step is:

    1. Indirecting a pointer to the underlying heap memory Obj occupies (returning the object Obj)
    2. Calling the copy constructor to create a temporary copy
    3. Storing the temporary copy in the collection

    You do not need to create this initial Obj on the heap, a stack allocated local will suffice as @Luchian Grigore has pointed out.

    Obj obj;
    objList.push_back(obj);
    

    You do not need to call delete on the copy in the collection, the STL collection will handle this memory itself when you remove the element, but you still will need to delete the original heap allocated object.

    It would be better if you stored your objects by std::shared_ptr. That way delete would be called when all references to the Obj were removed.

    std::vector< std::shared_ptr< Obj > > vec;
    vec.push_back( std::make_shared( new Obj() ) );
    

提交回复
热议问题