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

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

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

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

How to properly free the memory allocated by placement new?

Using the new expression does two things, it calls the function operator new which allocates memory, and then it uses placement new, to create the object in that memory. The delete expression calls the object’s destructor, and then calls operator delete. Yeah, the names are confusing. //normal version calls these two functions MyClass* pMemory = … Read more

Destroy and then construct new object using the same variable

I think the only way to make this really safe to use is to require the called constructor to be noexcept, for example by adding a static_assert: static_assert(noexcept(T(22, Brown, true)), “The constructor must be noexcept for inplace reconstruction”); T x(31, Blue, false); x.~T(); ::new (&x) T(22, Brown, true); Of course this will only work for … Read more

Array placement-new requires unspecified overhead in the buffer?

Update Nicol Bolas correctly points out in the comments below that this has been fixed such that the overhead is always zero for operator new[](std::size_t, void* p). This fix was done as a defect report in November 2019, which makes it retroactive to all versions of C++. Original Answer Don’t use operator new[](std::size_t, void* p) … Read more

tech