Is this program ill-formed?
#include <new>
struct A
{
int a;
int b;
};
struct B
{
int a;
};
int main()
{
void* p(operator new(sizeof(A)));
new (p) A();
static_cast<A*>(p)->~A();
new (p) B();
static_cast<B*>(p)->~B();
operator delete(p);
}
Note that we have a guarantee that p
will be correctly aligned for type A
. But how about the type B
? Does the standard mention anything? Is there a standard way to realign p
?
EDIT: I feel the accepted answer needs more explanation. operator new
must return a pointer correctly aligned for any object of that size, but of what type is that object going to be? It does not know (and alignment depends upon type), hence it must provide a pointer properly aligned for instances of all possible types and since a "smaller" type's maximum alignment is less than "bigger" type's, the pointer should be correctly aligned.