Is the operation of rewriting the value of object3 by the following source code valid in the current C++ standard?
#include <iostream>
void foreign_function(short* s);
int main() {
alignas(8) char object1[16];
short* p_object2 = new(object1 + 2) short(10); // Create object2 of type short
long* p_object3 = new(object1 + 8) long(100); // Create object3 of type long
foreign_function(p_object2);
std::cout << *p_object3 << std::endl;
}
void foreign_function(short* s) {
char* p_object4 = new(s) char(); // Create object4 of type char
char* pointer5 = p_object4 + 6; // (*) pointer arithmetic
new(pointer5) long(1000); // object3 is transparently replaceable by the new object ([basic.life] p8)
}
In particular, I am wondering if the pointer operation indicated by (*) is valid.
When object2 is created, object1 provides storage for object2 according to the [intro.object] p3, and therefore lifetime of object1 does not end.
https://timsong-cpp.github.io/cppwp/n4861/intro.object#3
https://timsong-cpp.github.io/cppwp/n4861/intro.object#4.2
https://timsong-cpp.github.io/cppwp/n4861/basic.memobj#basic.life-1.5
However, the lifetime of the second and third elements of object1, objects of type char, ends.
The same is true when creating object3.
Then, when object4 of type char is created, the lifetime of object2 ends.
In this case, object4 becomes a subobject of object1 according to [intro.object] p2.
The element of object1 that once existed at the same address as object4, i.e., the second element of object1, has already reached the end of its lifetime, but according to [intro.object] p2 that should not be a problem.
https://timsong-cpp.github.io/cppwp/n4861/intro.object#2
It seems to me that p_object4 can be used for pointer arithmetic according to [expr.add] p4.2.
https://timsong-cpp.github.io/cppwp/n4861/expr.add#4.2
However, [intro.object] p2 only specifies that object4 is a subobject of object1.
Can object4 really be properly treated as the second element of object1?
new(pointer5) long(1000);may cause alignment issues though.