1) Whole string is implemented with a char pointer (char*).
This is not a legal implementation. size()
and capacity()
and must be constant so you either need to store that information as pointer or integer variables.
2) Some parts of the string are implemented with a static array. Its size is equal to 40, and if length of the string exceeds 40, dynamic memory is allocated.
That array isn't a static member but this is legal since C++11 and is called small/short string optimization. One common way to implement this is
struct _internal
{
char * start;
char * end;
char * cap;
};
union guts
{
_internal ptrs;
char arr[sizeof(_internal)];
}
and the string would be a wrapper around guts
. This lets the array take up no more space than the pointer version but allows you to use the array untill you have more than sizeof(_internal) - 1
characters.