After learning that std::vector is unimplementable in pure C++, I was wondering if it is possible to write a dynamic array without evoking UB. We can't do pointer arithmetic without an array, which implies we cannot have a dynamic buffer with partially initizalized memory and treat it as an array; so std::vector must rely on the implementation defining some behavior where it would otherwise be UB.
Dynamic arrays are pretty ubiquitious data structures, and generally simple. The seemed impossibility of being able to implement this conformantly makes C++ seem like a not-so-general-purpose system language, IMO.
As so, my questions are:
N.B.: dynamic array is used here to denote a linear data structure that can grow/shrink "in place", like a std::vector or, similarly, a C buffer (m)alloced in the heap.
If std::vector
can't, then you can't either.
But I wouldn't worry about it. This is one of those cases where people have found a problem with the wording of the standard, that technically makes an extremely common use case undefined. But your vectors still work.
Now, the key: that's not because of magic innate to std::vector
, or to some particular std::vector
implementation: it's because the compiler doesn't perform absurd optimisations that make use of this undefined behaviour that somebody only just spotted while studying the text with a fine-toothed comb.
Perhaps it'll be tidied up in a future revision, but for practical purposes you do not need to worry about it, whether you use std::vector
or you use new[]
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With