OOPortal 





Operator Overloading  «Prev 
Overloading the operators new and delete

Placement syntax of the new operator

The placement syntax provides a comma-separated argument list used to select an overloaded operator new() with a matching signature.
These additional arguments are often used to place the constructed object at a particular address. This form of operator new uses the new.h header file.
For example:
//Placement syntax and new overloaded.
#include <iostream.h>
#include <new.h>

char*  buf1 = new char[1000]; //in place of free store
char*  buf2 = new char[1000];

class object {
public:
   .....
private:
   .....
};

void main(){
   object *p = new(buf1) object;  //allocate at buf1
   object *q = new(buf2) object;  //allocate at buf2
   .....
}

Placement syntax allows the user to have an arbitrary signature for the overloaded new operator.
This signature is distinct from the initializer arguments used by calls to new that select an appropriate constructor.
The allocator function is operator new or
operator new[],
which can be overloaded.
Two global placement operator new functions are provided by the standard library; you can define additional functions if you wish.
The allocator function takes a size_t as its first parameter, which is the number of bytes of memory to allocate. It returns a pointer to the memory. The placement syntax is a list of expressions in parentheses. The expression list is passed to the allocator functions after the size argument. The compiler chooses which overloaded operator new according to the usual rules of overload resolution.