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.
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.
Keep in mind that, what new T(...)
(called a "new-expression") does, is two things: allocating memory and initializing an object. You can tweak the initialization by writing constructors. For the allocation you write operator new
. So despite the name, operator new
does only one side of what a new expression does.
Placement new is there to put an object into pre-allocated memory. You cannot call constructors directly passing the pre-allocated memory as a this
pointer. The only thing you can do is use placement new: This turns allocation into a no-op, leaving only construction left to be done. This
inline void* operator new(size_t, void *p) throw()
{
return p;
}
is just the implementation of that no-op.
精彩评论