简体   繁体   English

C ++中Pascal字符串的数据布局

[英]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++: 在这里,“ pascal字符串”的最有效表示形式在C ++中看起来像一个字节,最大为255个字符。

  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)). 一个std::unique_ptr<Content> (与(1)中的Content相同)。 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. 但是,由于在指向数据的指针之前进行了填充,因此浪费了7个字节。 This would be similar to a std::vector with fixed capacity, so probably not very exiting, or? 这将类似于具有固定容量的std::vector ,因此可能不是很成熟,或者?

I find option (1) the most natural approach. 我发现选项(1)是最自然的方法。 This gives the user the flexibility to store the data on the stack, while (2) forces the use heap storage. 这使用户可以灵活地将数据存储在堆栈上,而(2)则强制使用堆存储。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM