Search code examples
c++c++11placement-new

Why would I call new without storing the ptr?


Today I was reading though some source code and I encountered this

Pool<C> *pool = accomodate_component<C>();
new(pool->get(id.index())) C(std::forward<Args>(args) ...);

And this line confused me

new(pool->get(id.index())) C(std::forward<Args>(args) ...);

I didn't even think that it was legal C++. As it turns out pool->get(id.index()) returns a size which told me that it could be possible to tell C++ explicitly how much size it should allocate.

I looked it up and yes it is defined that way void* operator new ( std::size_t count );

Now I know that this is legal C++ but what I don't know is its purpose.

Why would I ever call new(size) Foo();. Shouldn't this be a memory leak? And isn't it completely pointless? If I don't have the ptr how I would ever access it?


Solution

  • This is calling placement new which places an object into the location specified in parenthesis. With generalized unions accommodating class types I'd expect placement new to be more widely used: to change the tag to a class type you'll need to construct the object, probably using placement new (obviously, after manually destroying any object previously located in that spot, if any).

    Since the location of the newed object with placement new is readily known, there won't be any need to capture its address. Since the only way for placement new to fail is to have an exception thrown from the newly created object's constructor, there is also no point in checking the result.