Harish
Harish

Reputation: 69

Decreasing string capacity in C++

Why doesn't the string capacity adjust according to the resized number (15)?

int main()
{
    string str = "Hello";
    cout << "Original: " << str.capacity() << endl;
    str.resize(15);
    cout << "New: " << str.capacity() << endl;
    return 0;
}

Result:

Original: 22
New: 22

I'm new to programming, so your simple explanation will be much appreciated. Thanks!

Upvotes: 1

Views: 709

Answers (1)

Tharwen
Tharwen

Reputation: 3107

The only requirement is that the capacity is at least as large as the size. If you want to increase the capacity, use reserve, and if you want to use the smallest possible capacity for the current string size, use shrink_to_fit. Bear in mind that if you're doing this for performance reasons it's probably unnecessary though.

In this case the size is always going to be at least 22 characters due to small string optimisation.

Upvotes: 3

Related Questions