January 2019
Intermediate to advanced
512 pages
14h 5m
English
The simple_string class we have implemented has an obvious inefficiency—when the string is stored in the local buffer, we do not really need the pointer to the data. We know exactly where the data is, in the local buffer. We do need to know, somehow, whether the data is in the local buffer or in the externally allocated memory, but we don't need to use 8 bytes (on a 64-bit machine) just to store that. Of course, we still need the pointer for storing longer strings, but we could reuse that memory for the buffer when the string is short:
class small_string { ... private: union { char* s_; struct { char buf[15]; char tag; } b_; };};
Here, we use the last byte as a tag to indicate whether the string is stored locally ...