All STL containers allocate memory dynamically based on demand.
But the memory allocated is always greater than what is actually required so that it cope with future additions to the container without allocating additional memory.
This is done because memory allocation is time consuming.
Also too much memory allocation will unnecessarily waste memory.
So there is a balance between the 2.
So
size
returns the actual size of the contents of the container and
capacity
returns the total memory currently allocated.
Try this -
std::string s1;
for (int i = 0; i < 100; ++i)
{
s1.append("");
cout << "Size = " << s1.size() << ", Capacity = " << s1.capacity() << endl;
}