Search code examples
c++memory-layout

Data layout for pascal string in C++


How would the most efficient representation of a "pascal string" here one byte for the size and at most 255 characters look like in C++:

  1. A struct containing both size and data:

    struct Content
        {
        uint8_t size;
        std::array<uint8_t, 255> data;
        }; 
    

    This will store data directly on the stack, which should be fast, but the objects will take some stack space, and move operations are expensive

  2. A std::unique_ptr<Content> (Same Content as in (1)). An extra dereference is needed to access both size and data, but move operations are cheap.

  3. Putting the size on the stack and the data on the heap. This means that it is easy to access the size, and move operations are still cheap. However, 7 bytes are wasted because of padding before the pointer to the data. This would be similar to a std::vector with fixed capacity, so probably not very exiting, or?


Solution

  • I find option (1) the most natural approach. This gives the user the flexibility to store the data on the stack, while (2) forces the use heap storage.