1

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!

Harish
  • 69
  • 3
  • http://www.cplusplus.com/reference/string/string/shrink_to_fit/ "Requests the string to reduce its capacity to fit its size." Check the example code on this link, it's exactly what's your need to understand it. – MatthieuL Jun 29 '20 at 06:54
  • Most probably your compiler implements a minimal headroom of 22 for the allocation. So resizing to 15 will actually let you only store 15 chars but the original capacity of 22 is kept. This means that you can `push_back` up to 22 before the complete content is moved to a greater allocated place. – Jean-Marc Volle Jun 29 '20 at 06:55
  • `resize` resizes the string, it does not change the underlying memory, except you resize to more than the capacity is. Why do you think that your snippet reduce the capacity? Did you mix it up with `reserve`? – mch Jun 29 '20 at 06:55

1 Answers1

3

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.

Tharwen
  • 3,057
  • 2
  • 24
  • 36