In the C++ programming language, placement new is a form of the new operator that allows object construction into an existing memory buffer. Unlike other forms of new
, the new object does not have to be in heap memory. The pointer returned by placement new is the pointer provided as an argument, cast to the type of the new object and possibly initialized.
Placement new is necessary for hardware that expects a certain object at a specific hardware address. It is also required for the construction of objects that need to reside in a certain memory area, such as an area that is shared between several processors of a multiprocessor computer.[1]
Syntax
The syntax for placement new
:
p_var = new(p_place) typename;
where p_place
provides a pointer of type void
. When the user has provided the new
function, p_place
may also be the placement arguments to that function. p_var
is a previously declared pointer of type typename
. typename
can be any basic data type or user-defined object (enum
, class
, and struct
included). If typename
is of class type, the default constructor is called to construct the object.
The syntax for initialization is as for ordinary constructors:
p_var = new(p_place) type(initializer);
p_var = new(p_place) type [size];
Although an object created with the placement new is not normally deleted, it may be necessary to call its destructor. This is done with the following syntax:
p_var->~type();
See also
References
- ^ Stroustrup, Bjarne (1994), Design and Evolution of C++, Addison-Wesley, ISBN 978-0-201-54330-8, section Memory Management.
Further reading
- Stroustrup, Bjarne (1997), The C++ Programming Language (third ed.), Addison-Wesley, ISBN 978-0-201-88954-3
- IBM Documentation describing C++'s operator new
- Microsoft Visual Studio operator new documentation
- Tip of the day for July 18, 1998
- Franek, Frantisek (2004), Memory as a Programming Concept in C and C++, Cambridge University Press, ISBN 978-0-521-52043-0