c++paddingplacement-new

Is padding important when calling to placement new?


I want to construct B at the place for A.

struct A {
  size_t x;  // 8 bytes
  int i;     // 4 bytes
};           // padding 4 bytes

struct B {
  size_t x;  // 8 bytes
  bool b;    // 1 byte
};           // padding 7 bytes

int main() {
  A a;
  auto p = new(&a) B;
  // auto p = new(std::launder(&a)) B;  // is a bit better
}

Is this code well-defined? Will placement new touch padding bytes (e.g. set all to zeros) or it will work directly with the b bytes?

For example, two A structures are stored contiguously (right after first A::i goes second A::x). If placement new touches padding, second A's data will be corrupted.


Solution

  • There are several things to discuss here.