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
6/8/2020 8:23:53 PMKetan Lalcheta
7 AnswersNew Answer
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.
The capacity is not the same as the length. Internally it is creating a character array of length 15 as in char mystring; mystring = '\0'; here we have a character array that can contain up to 15 characters including the null character but the current length of the string is 0 characters. If I add additional characters... mystring = 'H'; mystring = 'i'; nystring = '\0'; now the string has a length of two but the array still has a capacity of 15.
The capacity is 15 since you can only store a maximum of 15 characters in the array before memory is allocated on the heap.
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.
Thanks Martin Taylor and Anthony Maina .... One more question... Why it is 15? Is it standard or depends on compiler to compiler?
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
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