Suppose you have an array of objects in C++ and you remove one of the objects from the array. When is that object’s destructor called? Since C++ does not have automatic garbage collecting, it would seem strange if the destructor was called right after being removed from the array. But does the object stay allocated until the array goes out of scope? That seems like it would lead to memory leaks.
Edit:
Instead of “remove” how about setting one of the elements of the array to a different object.
Also, what does happen when an element is removed from a std::vector?
When you declare a C++ array, it constructs all of the objects on the stack, and they stay there until the array itself is deleted:
Objects can’t be “removed” from this kind of array. When ArrayOfStrings goes out of scope, it automatically deletes all the strings in the array. If you edit an object in this array, that object itself is changed. You actually changed the string itself, not some pointer or reference.
If you have an array of pointers, then C++ constructs all of the pointers, but you have to manage what they point at yourself:
You can manually delete strings that the pointers in the array point to, but you have to do all of that yourself. When ArrayOfPointersToStrings goes out of scope, it WILL NOT delete anything the strings point at. If you edit a pointer without deleting it first, that’s a memory leak, and that’s bad.
If you have a std::vector, C++ constructs only some objects depending on how you construct it:
This creates a dynamic array of strings. It is possible to remove objects from a vector, in which case the vector instantly deletes it and rearranges the rest for you. If you edit an object in this array, that object itself is changed. You actually changed the string itself, not some pointer or reference.
To clarify comments: