传递给 placement new 的指针是否是指向其对象表示的非 UB 指针?

Is the pointer passed to placement new a non-UB pointer to its object representation?

struct foo {
   int a;
   int b;
};

std::array<char, sizeof(foo)> buffer;
foo a {1, 2};
foo* b {new (buffer.data()) foo};
std::memcpy(buffer.data(), &a, sizeof(foo));
a == *b; // the important part

我知道 placement new 使 b 的字段的值不确定,但随后的 memcpy,通过指向传递给 new 的缓冲区的指针,然后转 ba 的副本?还是有 UB,因为我没有 memcpy-ing 通过 new 返回的指针?

cppreference 对我来说有点太迟钝了,在这种情况下,无法弄清楚它是否已定义。

编辑:假设 buffer 正确对齐以使新位置有意义

Placement new

If placement_params are provided, they are passed to the allocation function as additional arguments. Such allocation functions are known as "placement new", after the standard allocation function void* operator new(std::size_t, void*), which simply returns its second argument unchanged. This is used to construct objects in allocated storage:

以上来自cppreference,所以你在memcpy后是正确的 'b'的内存内容和'a'

是一样的

来源:https://en.cppreference.com/w/cpp/language/new