tags:

views:

207

answers:

1
+5  Q: 

new 2nd param, c++

in an example i saw this line

Thing *pThing = new (getHeap(), getConstraint()) Thing(initval());

There was no explanation, function body or class definition. What does the 2nd parameter mean?

+18  A: 

It's an instance of 'placement new' syntax. It's for passing additional parameters to a custom memory allocation function.

Whereas this:

Obj* pObj = new Obj;

corresponds to allocating new memory by calling operator new with a single parameter of type size_t and the value of sizeof(Obj), and constructing a new Obj instance in the returned memory location,

Obj* pObj = new (param1, param2) Obj;

corresponds to calling an operator new with three parameters, sizeof(Obj) followed by param1 and param2 and constructing the Obj instance in the memory pointed to by the return value of the custom operator new.

Custom operator news can be defined globally, or as implicitly static class members, in which case they will only be considered for allocating class instances of that type or derived types.

There's more hows and whys in this FAQ.

Charles Bailey
A flawless answer - nothing can be added or removed.
Arafangion
This answer is pure gold
acidzombie24