top | item 27597730

(no title)

flyingswift | 4 years ago

Thanks! I am just learning C++ for a new gig, and coming from Javascript land, it is a lot to take in :)

discuss

order

layoutIfNeeded|4 years ago

Yikes. I feel sorry for your client in advance. One does not learn C++ “for a gig”, especially when coming from JS…

Karsteski|4 years ago

For all you know, this person is simply talking about a new job. Is it necessary to be so condescending..? Sigh

saagarjha|4 years ago

I would generally suggest avoiding reference stability here (extra heap allocations) and going with the offset-based approach mentioned in the other responses.

Kranar|4 years ago

I would generally suggest going for correctness over performance and the solution I provided is correct in the general case. Using an offset is only correct in the special case where objects will not be inserted or removed at an index less than the offset, otherwise you will end up with bugs as the offset becomes invalid upon such operations.

Furthermore, depending on the size of T, the performance penalty of the extra heap allocations is amortized over the cost of resizing the vector. That is vector reallocation is significantly faster for a unique_ptr<T> than it is for T when T is large and almost all memory allocators are tuned to allocate objects close together in space when they are allocated close together in time, so you don't lose the cache locality or need to worry about memory fragmentation.