When we delete a pointer, the object it points to will be deleted. However, this does not happen when pointer objects are stored in an STL container.
1 | // Deleting a pointer will delete the object to which the pointer points |
You can store objects in STL containers as well as pointers to objects. When STL objects call clear() or erase(), if the container holds object instances, they will be deleted. However, if the container holds object pointers, a memory leak occurs (only the pointers are deleted, but the objects they point to will not be deleted).
Consider the following code:
1 | // for(type varName:object) is a new feature in C++11 — range-based for loop. |
Running result:
It is clear from the results that although we called strVector.clear()/erase() to delete all objects (pointers), (as expected) and hoped to free their memory, the objects pointed to by the pointers still exist, leading to a memory leak.
The objects pointed to by the pointers stored in the STL container will not be automatically released when clear()/erase() clears the objects.
This is because clear()/erase() automatically calls the destructor of each object to release it, but when the container holds object pointers, using clear() only calls the pointer’s destructor, and the destructor does nothing. Thus, a memory leak occurs.
At this point, we need to manually manage the memory ourselves.
We can manually delete each object pointed to by the pointers in strVector using delete:
1 | for(auto &index:strVector){ |
Then we output the values of the objects pointed to by the pointers in strVectorCopy:
1 | for(auto &index:strVectorCopy){ |
Running result:
It can be seen that the objects pointed to by the pointers stored in strVector have been released, and at this time, we are accessing the memory block pointed to by a dangling pointer, resulting in undefined behavior.
When using STL, the following two points should be noted:
- STL containers operate by copying. When you put an element into a container, what is actually stored in the container is a copy of that element, and the memory for the copy is automatically allocated by the STL container. When you delete this element, the STL will call the destructor of that element itself to reclaim that memory.
- If you put a pointer into the container, when deleting the element, the container is only responsible for reclaiming the memory occupied by the pointer itself, but will not reclaim the content pointed to by the pointer.