Search code examples
c++memory-managementplacement-new

Magic in placement new?


I'm playing with dynamic memory allocation "by hand" and I wanted to see how placement new is implemented by guys from MS but when debugging I "stepped into" it moved me to code:

inline void *__CRTDECL operator new(size_t, void *_Where) _THROW0()
{   // construct array with placement at _Where
return (_Where);
}

Could anyone explain to me how on earth this code places my object into place pointed by my pointer when all I can see in this code is line with return statement with what I've supplied as an argument. I don't think that saying in comment what I would like this fnc to do is actually enough for it to work. Thank you for any constructive answers.


Solution

  • The purpose of operator new is only to allocate memory for an object, and return the pointer to that memory. When you use placement new, you're essentially telling the compiler "I know this memory is good, skip allocation, and use this pointer for my object." Your object's constructor is then called using the pointer provided by operator new whether or not it was memory that was just allocated, or specified by using placement new. operator new itself does not have any bearing on how your object is constructed.