From what I get, it should normally be correct to use a placement-new for reconstructing a type like this:
A a;
auto aptr = new(&a) A();
So I decided to try it with a class member like this:
struct PackedTest {
char a = 0;
int b = 0;
void setb() {
new(&b) int(5);
}
};
int main() {
PackedTest p;
std::cout << sizeof(p) << "\n";
std::cout << p.b << "\n";
p.setb();
std::cout << p.b << "\n";
}
and everything seems fine. But then I thought if we can always do the same with struct members? Let's assume that we have following packed struct:
struct __attribute__((packed)) PackedTest {
char a = 0;
int b = 0;
void setb() {
new(&b) int(5);
}
};
Is this code still valid or it is undefined behavior? Because in previous case, alignment of b
was equal to alignment of int
, so placement-new should be fine. But in this new struct, alignment of b
is 1
which is less than alignment requirement int
.
Should I always add alignas(T)
like:
struct __attribute__((packed)) PackedTest {
char a = 0;
alignas(int) int b = 0;
void setb() {
new(&b) int(5);
}
};
as a rule of thumb for any variable that will be used as buffer for placement-new (though it seem this alignas
is somehow affects whole structure, not just b
)?