Skip to Content
Hands-On Design Patterns with C++
book

Hands-On Design Patterns with C++

by Fedor G. Pikus
January 2019
Intermediate to advanced
512 pages
14h 5m
English
Packt Publishing
Content preview from Hands-On Design Patterns with C++

Additional optimizations

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 ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Structural Design Patterns in Modern C++

Structural Design Patterns in Modern C++

Umar Lone

Publisher Resources

ISBN: 9781788832564Supplemental Content