Memory Management in C : clearing vectors vs. deleting objects
In C , it's crucial to understand how memory is managed. When dealing with dynamic data structures like vectors and pointers, releasing allocated memory appropriately is essential.
Consider the following code example:
<code class="cpp">tempObject obj1; tempObject obj2; vector<tempObject> tempVector; tempVector.pushback(obj1); tempVector.pushback(obj2); tempVector.clear();</code>
The question arises, does calling clear() on a vector automatically release the memory occupied by the objects within it?
For vectors holding objects
While calling clear() destroys the objects within the vector, it does not release the allocated memory. Iterating through the vector elements and deleting them individually won't help either.
To effectively free the memory associated with the vector, you can use the following strategy:
<code class="cpp">vector<tempObject>().swap(tempVector);</code>
This creates an empty vector with no allocated memory and swaps it with tempVector, effectively deallocating the memory.
For vectors holding pointers to objects
The behavior is similar for vectors holding pointers to objects. Calling clear() on a vector of pointers will destroy the pointers but not the objects they refer to. To free the memory, you have two options:
C 11's shrink_to_fit function
C 11 introduced the shrink_to_fit function, which can be called after clear(). While it theoretically shrinks the vector's capacity to fit its size, it's important to note that this is a non-binding request and may be ignored by some implementations.
The above is the detailed content of Does `vector::clear()` Release Memory of Objects Stored Within?. For more information, please follow other related articles on the PHP Chinese website!