I'm aware that this question has already been asked and somewhat answered in the past.
However, I've a doubt on a detail that hasn't been cleared out yet (or at least for which I couldn't find a QA).
Consider the following code:
T *mem = allocator_traits::allocate(allocator, 10);
allocator_traits::construct(allocator, mem+1, params...);
I'm constructing an object at mem[1] even if the object at mem[0] doesn't exist yet.
As far as I understand, pointer arithmetic is well defined over a created array of not-constructed objects. However, this QA doesn't answer this specific case:
I should have stated that when I said storage + i will be well-defined under P0593, I was assuming that the elements storage[0], storage[1], ..., storage[i-1] have already been constructed. Although I'm not sure I understand P0593 well enough to conclude that it wouldn't also cover the case where those elements hadn't already been constructed.
In other terms, the author says that this could be UB. On the other side, it would make it impossible for an std::vector implementation to do something like this:
buf_end_size = newbuf + sizeof(T) * size();
Since I expect it to be valid code (and I've seen this in some implementations), it would mean that pointer arithmetic is well defined for any value of i also when objects aren't constructed.
So, my question is: is this UB or I can safely do pointer arithmetic on the pointer returned by allocate in any case, for example if I want to construct the element at position 1 before that at position 0? Also, does the answer change between C++17 and C++20?
I think this is a relevant text in the standard about pointer arithmetic. Basically if you do addition/subtraction between two pointers and the result does not go out of bound of a reserved array, then the behavior is well-defined. I believe what you are trying to do is well-defined, because you have reserved an array of memory.
https://eel.is/c++draft/expr.add#5
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