Middle
What happens to the vector object when a new element is added?
sobes.tech AI
Answer from AI
When adding a new element to a std::vector:
- Capacity check: The vector checks if the current allocated memory (
capacity()) is sufficient to hold the new element. - Allocating new buffer: If the capacity is insufficient, the vector allocates a new, larger memory buffer (usually 1.5 or 2 times larger than the current).
- Copying/moving elements: All existing elements are copied (or moved, if possible) from the old buffer to the new one.
- Old buffer deallocated: The old memory buffer is released.
- Adding the new element: The new element is added to the end of the new buffer.
- Updating size and capacity: Internal counters are updated.
If the current capacity is sufficient, the new element is simply constructed at the end, and only the size counter is updated.
Example:
#include <vector>
#include <iostream>
struct MyObject {
int id;
MyObject(int i) : id(i) { std::cout << "Construct " << id << std::endl; }
MyObject(const MyObject& other) : id(other.id) { std::cout << "Copy Construct " << id << std::endl; }
MyObject(MyObject&& other) : id(other.id) { std::cout << "Move Construct " << id << std::endl; other.id = -1;}
~MyObject() { std::cout << "Destruct " << id << std::endl; }
};
int main() {
std::vector<MyObject> v; // Capacity is 0
std::cout << "Adding 1:" << std::endl;
v.push_back(MyObject(1)); // New buffer (size 1), construct 1, destruct temp
std::cout << "Adding 2:" << std::endl;
v.push_back(MyObject(2)); // Reallocation (capacity 2), move 1, construct 2, destruct 1, destruct temp
std::cout << "Adding 3:" << std::endl;
v.push_back(MyObject(3)); // Reallocation (capacity 4), move 1, move 2, construct 3, destruct 1, destruct 2, destruct temp
std::cout << "Adding 4:" << std::endl;
v.push_back(MyObject(4)); // No reallocation (capacity 4), construct 4, destruct temp
// Program ends, vector destructed
// Destruct 1, Destruct 2, Destruct 3, Destruct 4 (from final buffer)
return 0;
}
The output may vary slightly depending on the STL implementation, but the logic of reallocation and moving remains.