3 ms·
If I want pointer stability, I usually use resize() + operator[] instead of reserve, though of course this requires a cheap default constructor. reserve + push_
by sagarm 4y ago
If I want pointer stability, I usually use resize() + operator[] instead of reserve, though of course this requires a cheap default constructor. reserve + push_back feels more likely to subtly rather than loudly break due to future changes.
- deleted 4y ago[deleted]
- dataflow 4y agoIs resize() guaranteed to respect geometric growth? I know it has for me in practice, but this made me question everything. And more generally, it's nice when you can do that, but it's not a substitute. From an API standpoint it seems really weird for reserve() and resize() to differ in what they set the target capacity to - the natural thing would seem to be that they should only differ in the initialization + resizing, not in the reservation.
- vitus 4y agoIf you want pointer stability, then reserve + push_back is sufficient to avoid reallocations, if you have an upper bound on the final size (which you need anyways to use resize effectively). Else, you should probably be storing a vector<unique_pointer<T>> which has its own downsides (mostly around locality). Side note: vector::operator[] is UB for out-of-bounds access; if your goal is for something to break loudly, you should be using vector::at().