Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should object be explicitly deleted after removing it from a Vector?

Let's say I have a Vector v that contains 100 objects of class Scenario which is composed of 10 different types of objects.In order to permanently delete Scenario and all its objects at index 5 of Vector v , which one of the following is correct way.

1.   v.removeElementAt(5);

OR:

2.   Scenario s=(Scenario) v.elementAt(5); 
     v.removeElementAt(5);
     s=null;

OR:

3.   Scenario s=(Scenario) v.elementAt(5); 
     s.makeAllObjectsNull();//explicitly assign null to 10 objects inside Scenario e.g. object1=null object2=null and so on
     v.removeElementAt(5);
     s=null;
like image 887
Faisal Bahadur Avatar asked Nov 16 '15 14:11

Faisal Bahadur


People also ask

Does deleting a vector delete its contents?

Yes, the vector 's destructor will be called, and this will clear its contents.

Do vectors need to be deleted?

The vector (like all standard containers) owns the objects inside it. So it is responsible for destroying them. Note: If you vector contains pointers then it owns the pointers (not what the pointers point at). So these need to be deleted.

Can you delete a vector?

One way of deleting a vector is to use the destructor of the vector. In this case, all the elements are deleted, but the name of the vector is not deleted. The second way to delete a vector is just to let it go out of scope. Normally, any non-static object declared in a scope dies when it goes out of scope.


1 Answers

Does an object need to be explicitly deleted after deleting it from a Vector? in simple word, all object that haven't any reference from another object is legible to be GC.

So any case of your code get that condition, then the object will be GC.

for example if a Scenario object has only referent from that vector, then:

v.removeElementAt(5);

the only reference has gone, and it will be legible to be GC.

another thing to tell here. when you doing this:

 Scenario s = (Scenario) v.elementAt(5); 
 v.removeElementAt(5);
 s = null;

You just declared another reference s and then set it to null, so it's not necessary to this.

like image 77
Salah Avatar answered Oct 05 '22 05:10

Salah