Suppose you create a vector with this line:
std::vector<int> v;
IIRC, std::vector allocates memory for an int array of capacity 10 and assigns a size of 0.
When you do a push_back(), std::vector checks that the size (how many elements are actually in the array) is not greater than the capacity (the real size of the array). If it isn't, the size is incremented and the last element is assigned to the parameter passed. If it is, the vector is manually copied to a different location. In other words, the copy constructor and the destructor of each of the elements is called, rather than making a call to realloc(). This is important to know, and I'll explaing why later. The destination array is always twice as big as the original, so if before the push_back() size==10 and capacity==10, after it size==11 and capacity==20.
Let's take the following class for example:
1 2 3 4 5 6 7 8 9
|
struct A{
int *a;
A(){
this->a=new int;
}
~A(){
delete this->a;
}
};
|
This class is not suitable to be used as
std::vector<A>
, but it can be used as
std::vector<A *>
.
Why? Because, since the class is using the default copy constructor, which
just copies each of the elements, copy->a will point to the same int as original->a. When the original is destructed, original->a will point to an invalid location, and by extension so will copy->a.
On the other hand, a vector of pointers to objects will never cause this kind of trouble.
When an element is removed from the vector (at least when it's not the last element), it's only destructed, but its memory is not freed. This is important to know when using vectors with large or many objects.