Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to use "delete"?

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; in the line where i note in below code, will the Obj still be stored in objList?

struct Obj {
    int u;
    int v;
};

vector<Obj> objList;

int main() {
    for(int i = 0; i < 10; i++) {
        Obj *obj = new Obj();
        obj->u = i;
        obj->v = i + 1;
        objList.push_back(*obj);
        // Should i use "delete Obj;" here? 
    }
}
like image 900
LoveTW Avatar asked Mar 27 '12 11:03

LoveTW


People also ask

When to use delete [] or delete?

delete is used for one single pointer and delete[] is used for deleting an array through a pointer.

Why delete is used?

Delete has its roots in Latin and was first used to mean destroy. In modern usage, delete means to remove completely. Delete used in writing means to edit by removing, often done by drawing a line through the text to be deleted .

Should you use delete in C++?

delete and free() in C++ In C++, the delete operator should only be used either for the pointers pointing to the memory allocated using new operator or for a NULL pointer, and free() should only be used either for the pointers pointing to the memory allocated using malloc() or for a NULL pointer.


2 Answers

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() ) );
like image 117
Konrad Avatar answered Nov 11 '22 21:11

Konrad


Yes, you should.

There should be a corresponding delete for every new in your program.

But your program doesn't need dynamic allocation:

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

Also, your syntax was wrong - objList.push_back(*Obj); // should be *obj, not *Obj

like image 45
Luchian Grigore Avatar answered Nov 11 '22 21:11

Luchian Grigore