3 ms·
Right, in case they're heap allocated, the worst-case alignment requirement of malloc, as well as free() without a size is likely to force implementations to ro
by pornel 6y ago
Right, in case they're heap allocated, the worst-case alignment requirement of malloc, as well as free() without a size is likely to force implementations to round it up to at least 8 or 16 bytes for both.
- ncmncm 6y agoNo. The result of std::string("foo") is exactly the same size as of std::string("foofoo"). They take up exactly the same number of bytes in the free store, on the stack, in a hash table, what have you. When the string is very long, it occupies two stretches of storage, one exactly the same size as std::string("foo"), plus another stretch big enough for the long sequence plus whatever overhead heap allocation adds. But that is different from the examples given. For the cases cited, there is no indirection of any kind. The bytes are right there in the std::string object.
- pornel 6y agoWe just interpret "space in memory" at different levels of indirection. If you try to create std::string("verylong…") with more characters than you have memory, you run out of memory, so it "takes up space in memory", even though std::string has the same size as always. Bonus fact: *"foo" and *"foofoo" in Rust dereference to 3 bytes and 6 bytes, respectively. It's neither a pointer nor the first char.
- zabzonk 6y agoI actually (and pedantically, I'm afraid) meant that neither in C or C++ is it true that "foofoo" takes up double the size of "foo" - both will have a zero character at the end. The sizeof operator when applied to each will also return values that indicate that one is not double of the value of the other.
- brundolf 6y agoI was approximating for the sake of demonstration (as stated in the note that followed)