Tuesday, June 17, 2008

c++ new can has argument! (without operator overloading)

After using C++ for years, first time i relised that the new operator can accept argument, and it is quite useful. the usefulness this feature that i can think of are as follow:
  • no "delete" and "new" for replacing a unwanted object instance, simply call obj.~TYPE and new (&obj) TYPE, no memory manipulation required
  • allow object instances to be placed side by side (array), this allow object to be accessed faster and avoid memory segmentation
  • object-oriented, support object construction and destruction

this feature is best use for object pooling such as thread pool, hash table (see sauerbraten)

IBM c++ doc has a very good introduction about this.

The placement syntax is commonly used to invoke the global placement new
function. The global placement new function initializes an object or objects at
the location specified by the placement argument in the placement new
expression. This location must address storage that has previously been
allocated by some other means, because the global placement new function does
not itself allocate memory. In the following example, no new memory is allocated
by the calls new(whole) X(8);, new(seg2) X(9);, or new(seg3) X(10); Instead, the
constructors X(8), X(9), and X(10) are called to reinitialize the memory
allocated to the buffer whole. Because placement new does not allocate memory,
you should not use delete to deallocate objects created with the
placement
syntax. You can only delete the entire memory pool (delete whole). In the
example, you can keep the memory buffer but destroy the object stored in it by
explicitly calling a destructor.

No comments: