Consider the following code:
#include <string>
struct S { std::string str; };
int main() {
S *data = static_cast<S*>(operator new(sizeof(S) * 3));
new (&data[1]) S(); // (1)
new (data + 2) S(); // (2)
data[2].~S(); // (3)
data[1].~S(); // (4)
operator delete(data);
}
My understanding is that lines (2)-(4) have perfectly valid behavior.
However, I'm not sure about line (1)
: on the one hand, I never access the non-existing object data[1]
because I only need its address. On the other hand, I do by writing data[1]
, thus possibly invoking undefined behavior.
Is &data[1]
defined when data
is an allocated chunk of memory, but there is no object or subobject at data + 1
?