0

I would like to make my own implementation of the c++ std::basic_string template class for a project of mine and I would like to know the logic behind it.

For example: I heard that at first the c++ std::basic_string isn't a dynamically allocated string and in fact is a 19 long c string or null terminated string, if the string needs to be longer then it will become a dynamically allocated string, which improves the speed.

As a question I would like to know how to manage the memory of the string, like, if you need more space you would reallocate memory or allocate another memory block and connect the 2 memory blocks somehow to improve the performance, but I think that it will significantly improve the complexity of the code.

Claudiu HBann
  • 56
  • 1
  • 9
  • There are two types of string, string (1 byte per char) and wstring (2 bytes per char). And the both use a lot of the same logic which is implemented in std::basic_string. std::string has a lot of implementation details, like short-string optimization etc. (See https://stackoverflow.com/questions/10315041/meaning-of-acronym-sso-in-the-context-of-stdstring/10319672#10319672, where SSO is short string optimization). – Pepijn Kramer Aug 27 '21 at 11:58
  • *if you need more space you would reallocate memory or allocate another memory block and connect the 2 memory blocks somehow to improve the performance* That is not allowed. The `data` function must return a pointer where `[str.data(), str.data()+str.size()]` are valid and contains the contents of the string. This is also required to be done in constant time. – NathanOliver Aug 27 '21 at 12:01
  • In other words : the standard library has already thought about a lot of the memory managment and you don't need to worry about it unless you really really need performance optimization. – Pepijn Kramer Aug 27 '21 at 12:02
  • Related video: https://www.facebook.com/Engineering/videos/10151029396848109 – Aykhan Hagverdili Aug 27 '21 at 12:11

0 Answers0