Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

What is the underline implement of the c++ placement new?

T *p = ::operator new(sizeof(T));

And then

new (p) T;

I wonder how the syntax is working as the placement new is defined as:

void* operator new(std::size_t, void*)

The second argument void* seems point to the constructor to the object, so how cpp connect the new (p) T to the void*?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

In gcc libsupc++ the implement 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; }

So is it compiler responsible for translate the syntax new(*T) T to the calling of a placement operator new ?

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading