Do I really have to worry about alignment when using placement new operator?

When you call placement new on a buffer: A *a = new (buf) A; you are invoking the built-in void* operator new (std::size_t size, void* ptr) noexcept as defined in: c++11 18.6.1.3 Placement forms [new.delete.placement] These functions are reserved, a C++ program may not define functions that displace the versions in the Standard C++ library … Read more

How C++ placement new works?

It’s really, really simple: new can be thought of as doing two things: Allocating the memory. Placement-constructing the object in the allocated memory. There’s no guarantee that malloc is actually used by the implementation, but typically it is. You cannot assume it about the implementation, but for the purpose of understanding it’s an OK assumption. … Read more

treating memory returned by operator new(sizeof(T) * N) as an array

The issue of pointer arithmetic on allocated memory, as in your example: T* storage = static_cast<T*>(operator new(sizeof(T)*size)); // … T* p = storage + i; // precondition: 0 <= i < size new (p) T(element); being technically undefined behaviour has been known for a long time. It implies that std::vector can’t be implemented with well-defined … Read more

Placement new and assignment of class with const member

There is nothing that makes the shown code snippet inherently UB. However, it is almost certain UB will follow immediately under any normal usage. From [basic.life]/8 (emphasis mine) If, after the lifetime of an object has ended and before the storage which the object occupied is reused or released, a new object is created at … Read more

Is there a (semantic) difference between the return value of placement new and the casted value of its operand?

Only a can safely be used to directly access the Foo object created by the placement new-expression (which we’ll call x for ease of reference). Using b requires std::launder. The value of a is specified in [expr.new]/1: If the entity is a non-array object, the result of the new-expression is a pointer to the object … Read more