3 ms·
Is your first example really equivalent to Box<str>? I would have expected something like using BoxStr = std::unique_ptr<Str>; where Str is defined as
by tylerhou 4y ago
Is your first example really equivalent to Box<str>? I would have expected something like
using BoxStr = std::unique_ptr<Str>;
where Str is defined as
struct Str {
size_t len;
char data[];
};
The difference is that the len is stored on the heap, and the data is stored inline with the length. Unfortunately C++ does not support flexible array members so this syntax is not actually valid.
Edit: Never mind, after reading the article Rust does use the above representation because Box holds a “fat” pointer to str, which stores it’s length on the stack. So BoxStr is the correct equivalent, because &[u8] is not equivalent to u8*, it’s equivalent to std::span<u8>.
- steveklabnik 4y agoYour parent is correct, the length is stored alongside the pointer, not on the heap with its data. This is true for any "dynamically sized type," not just Box<str>. &str is also a (pointer, length) pair, for example.