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;
Yes, the vector 's destructor will be called, and this will clear its contents.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With