3 ms·
> Google also proposed uninitialized resize What would be the practical difference to std::string::reserve?
by spacechild1 3y ago
> Google also proposed uninitialized resize
What would be the practical difference to std::string::reserve?
- jeffbee 3y agoReserve sets the capacity, not the size. If you were to reserve and overwrite the buffer, the size is still wrong. Now if you resize, STL overwrites your contents with value initialized chars.
- spacechild1 3y agoOf course, you need to call push_back() or insert() to add the data. Actually, insert() wouldn't even require reserve() in the first place. I guess the idea of uninitialized resize is that you reserve the space, bump the size, and then you can directly set the new members with operator[]. If your input data is not contiguous, and would need to use push_back() otherwise, you can save a few if-checks. But that's pretty much it, I assume.
- gary_0 3y agoAlso I don't think the Standard requires that data() returns a valid pointer after only calling reserve(), so it's technically UB.
- zabzonk 3y agoi think you may have misunderstood the standard - data() will always return a valid pointer, but the pointer returned may be invalidated by any number of functions: string s; s.reserve(50); char * p = s.data(); // ok so far s.reserve(100); // now p may be invalid
- deleted 3y ago[deleted]