Re:Appending to an std:string character-by-character: how do...
by jeffbee on Thursday October 26, 2023 @08:18PM
(#38033286)
Google also proposed uninitialized resize, and the ability to treat string as if it were unique_ptr, by just giving it some already-allocated buffer. You can tell they use these internally because the fingerprints of these features are all over the protocol buffers open source libraries. I believe none of them have been adopted by the standard.
[ Parent
| on HN ]
Re:Appending to an std:string character-by-character: how do...
by terrelln on Thursday October 26, 2023 @09:02PM
(#38033540)
folly provides functions to resize std::string & std::vector without initialization [0].
[0] https://github.com/facebook/folly/blob/3c8829785e3ce86cb821c...
Re:Appending to an std:string character-by-character: how do...
by jeffbee on Thursday October 26, 2023 @09:12PM
(#38033598)
Yeah, it's nice! And Abseil does it, IFF you use LLVM libc++.
https://github.com/abseil/abseil-cpp/blob/master/absl/string...
The standard adopted it as resize_and_overwrite. Which I think is a little clunky.
Re:Appending to an std:string character-by-character: how do...
by spacechild1 on Thursday October 26, 2023 @09:06PM
(#38033565)
> Google also proposed uninitialized resize
What would be the practical difference to std::string::reserve?
Re:Appending to an std:string character-by-character: how do...
by jeffbee on Thursday October 26, 2023 @09:19PM
(#38033632)
Reserve 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.
Re:Appending to an std:string character-by-character: how do...
by gary_0 on Thursday October 26, 2023 @09:26PM
(#38033666)
Also I don't think the Standard requires that data() returns a valid pointer after only calling reserve(), so it's technically UB.
Re:Appending to an std:string character-by-character: how do...
by zabzonk on Thursday October 26, 2023 @11:40PM
(#38034445)
i 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
Re:Appending to an std:string character-by-character: how do...
by spacechild1 on Saturday October 28, 2023 @10:01AM
(#38049869)
Of 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.