What is placement new?

Answer Posted / ritesh pal

When you want to call a constructor directly, you use the placement new. Sometimes you have some raw memory that's already been allocated, and you need to construct an object in the memory you have. Operator new's special version placement new allows you to do it.
class Widget
{
public :
Widget(int widgetsize);
...
Widget* Construct_widget_int_buffer(void *buffer,int widgetsize)
{
return new(buffer) Widget(widgetsize);
}
};
This function returns a pointer to a Widget object that's constructed within the buffer passed to the function. Such a function might be useful for applications using shared memory or memory-mapped I/O, because objects in such applications must be placed at specific addresses or in memory allocated by special routines.

Is This Answer Correct ?    0 Yes 0 No



Post New Answer       View All Answers


Please Help Members By Posting Answers For Below Questions

how to use C++?

2070


What is a terminating character in c++?

770


Can you explain polymorphism?

584


Distinguish between a # include and #define.

653


What causes polymorphism?

577






Write a function that swaps the values of two integers, using int* as the argument type?

610


What does ctime() do?

618


What is the need of a destructor?

640


Explain pass by value and pass by reference.

598


Why is main function important?

588


What are the unique features of C++.

575


What is a set in c++?

533


What is a list in c++ stl?

697


It is possible to build a C++ compiler on top of a C compiler. How would you do this?

546


c++ program to swap the objects of two different classes

1767