Wednesday, December 15, 2010

Allocate object at predefined memory

Tip                   :   Placement new technique: You can decide on which memory address your class object to be allocated.
Details          :    Usually we use new operator to allocate objects. The new operator will allocate memory for object and calls the object’s constructor. We can construct our object in predefined memory location by using Placement new.
In placement new, you can pass the preferred memory location to the new operator at which the object to be constructed. During placement new, the new operator just calls the constructor. Responsibility of memory allocation is ours. After usage we should call the destructor manually to delete the object. Please see the following code block about usage of placement new, which is self explanatory.




The advantages of placement new are as follows -
1) We can allocate a pool of memory/block and construct objects on our wish.
2) This prevents memory allocation failure fear in runtime, because pool of memory is already allocated.
3) Object creation will be a bit faster, because memory is already allocated and only the constructor is to be called.
4) Since you can place your objects at your preferred memory locations, it is very useful in embedded programming. For instance the hardware may be placing 255 bytes of data at memory location – 0×1000. In that case, write a class with an array of 255 Bytes as member variable and construct the object at 0×1000. Now you can access the data by using that object.

And one more interesting information – The placement new is the only scenario in which we are legally allowed to call destructor explicitly as per C++ standards. The new ‘New’ information is interesting.. right..? J

Reference    :

Posted By :Krishnaraj S.

No comments:

Post a Comment