This is a follow up to this other question about memory re-use. As the original question was about a specific implementation, the answer was related to that specific implementat
int *in = reinterpret_cast
(buffer); // Defined behaviour because alignment is ok
Correct. But probably not in the sense you'd expect. [expr.static.cast]
A prvalue of type “pointer to
cv1 void
” can be converted to a prvalue of type “pointer tocv2 T
”, whereT
is an object type andcv2
is the same cv-qualification as, or greater cv-qualification than,cv1
. If the original pointer value represents the addressA
of a byte in memory andA
does not satisfy the alignment requirement ofT
, then the resulting pointer value is unspecified. Otherwise, if the original pointer value points to an objecta
, and there is an objectb
of typeT
(ignoring cv-qualification) that is pointer-interconvertible witha
, the result is a pointer tob
. Otherwise, the pointer value is unchanged by the conversion.
There is no int
nor any pointer-interconvertible object at buffer
, therefore the pointer value is unchanged. in
is a pointer of type int*
that points to a region of raw memory.
for (int i=0; i
Is incorrect. [intro.object]
An object is created by a definition, by a new-expression, when implicitly changing the active member of a union, or when a temporary object is created.
Noticeably absent is assignment. No int
is created. In fact, by elimination, in
is an invalid pointer, and dereferencing it is UB.
The later float*
all also follows as UB.
Even in absence of all the aforementioned UB by proper use of new (pointer) Type{i};
to create objects, there is no array object in existence. The (unrelated) objects just happens to be side by side in memory. This means pointer arithmetic with the resulting pointer is also UB. [expr.add]
When an expression that has integral type is added to or subtracted from a pointer, the result has the type of the pointer operand. If the expression
P
points to elementx[i]
of an array objectx
withn
elements, the expressionsP + J
andJ + P
(where J has the value j) point to the (possibly-hypothetical) elementx[i+j] if 0 ≤ i+j ≤ n;
otherwise, the behavior is undefined. Likewise, the expressionP - J
points to the (possibly-hypothetical) elementx[i−j] if 0 ≤ i−j ≤ n;
otherwise, the behavior is undefined.
Where hypothetical element refers to the one past-the-end (hypothetical) element. Note that a pointer to a one past-the-end element that happens to be at the same address location as another object doesn't point to that other object.