T *p = ::operator new(sizeof(T));
new (p) T;
I wonder how that syntax is working, given that placement new is declared as:
void* operator new(std::size_t, void*)
The second argument void*
seems point to the storage of the object, so how does C++ connect the new (p) T
to the void*
?
In gcc libsupc++ the implementation is simply:
// Default placement versions of operator new.
_GLIBCXX_NODISCARD inline void* operator new(std::size_t, void* __p) _GLIBCXX_USE_NOEXCEPT
{ return __p; }
_GLIBCXX_NODISCARD inline void* operator new[](std::size_t, void* __p) _GLIBCXX_USE_NOEXCEPT
{ return __p; }
Is the compiler responsible for translating the syntax new(*T) T
to the calling of a placement operator new
?
Is it compiler's responsibility to translate the syntax new(*T) T to the calling of a placement operator new?
Yes, exactly.
Placement new
can not be implemented as a library function, it needs special handling from the compiler anyway. The actual implementation that you saw in the libsupc++ source code can be misleading here, as most of the crucial properties of a placement new call are not reflected by that implementation.