String capacity | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

String capacity

Hi Refer below code : https://code.sololearn.com/c0ts9jWZM4CN/?ref=app I do understand that initial capacity is 15 for empty string and it will not resize till number of characters are not more than 15. As soon as we are going to add character number 16 , it's gonna double the capacity. This behaviour is almost same as vector capacity... But I really don't understand why initial empty string has 15 as capacity unlike zero in case of vector.. Thanks for your help 👍 Regards Ketan

8th Jun 2020, 8:23 PM
Ketan Lalcheta
Ketan Lalcheta - avatar
6 Answers
+ 3
To expound on what Martin Taylor has said,the basic_string class uses an anonymous union(which is just a union without a name) composed of a character array and an integer space.The character array length is actually 16 not 15,so as to cater for the null terminating character. When the string's size is <= 16,all of its characters are stored in the array.If its size goes beyond 16,then space is allocated on the heap,all the characters copied onto the newly acquired memory and the current capacity of the string is stored in the integer space.
8th Jun 2020, 9:23 PM
Anthony Maina
Anthony Maina - avatar
+ 1
The capacity is 15 since you can only store a maximum of 15 characters in the array before memory is allocated on the heap.
9th Jun 2020, 8:36 AM
Anthony Maina
Anthony Maina - avatar
+ 1
No the string is stored in the heap since you exceeded the capacity of the character array. In your case the internal array is not used,the compiler directly allocates memory on the heap. For most implementations that I know of,15 is the initial capacity as it corresponds to maximum number of character that can be stored in the internal array.
9th Jun 2020, 9:16 AM
Anthony Maina
Anthony Maina - avatar
0
Thanks Martin Taylor and Anthony Maina .... One more question... Why it is 15? Is it standard or depends on compiler to compiler?
9th Jun 2020, 8:31 AM
Ketan Lalcheta
Ketan Lalcheta - avatar
0
I updated code now.. Instead of empty string at start, I am having initialisation with 16 characters. This is giving me initial capacity as 16... Expected also as it has to store 16 characters... Hope this 16 characters long string is also on stack as long as we don't exceed to initial capacity. Now my concern is that why only 15 as initial capacity for empty string? Is it compiler dependent or it can't go beyond 15 for empty string unlike now I am getting as 16
9th Jun 2020, 8:44 AM
Ketan Lalcheta
Ketan Lalcheta - avatar
0
Oh something new for me.... I never thought string declared and not modifying at all may also be allocated on heap.... Too strange to digest as I never thought of this
9th Jun 2020, 11:12 AM
Ketan Lalcheta
Ketan Lalcheta - avatar