This article may have been previously nominated for deletion: Wikipedia:Articles for deletion/Placement syntax exists. It is proposed that this article be deleted because of the following concern: If you can address this concern by improving, copyediting, sourcing, renaming, or merging the page, please edit this page and do so. You may remove this message if you improve the article or otherwise object to deletion for any reason. Although not required, you are encouraged to explain why you object to the deletion, either in your edit summary or on the talk page. If this template is removed, do not replace it. This message has remained in place for seven days, so the article may be deleted without further notice. Find sources: "Placement syntax" – news · newspapers · books · scholar · JSTOR Nominator: Please consider notifying the author/project: {{subst:proposed deletion notify|Placement syntax|concern=[[WP:NOTHOWTO]]}} ~~~~ Timestamp: 20081120190517 19:05, 20 November 2008 (UTC) Administrators: delete |
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 the placement new is the pointer provided as an argument casted to the type of the new object.
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.
Syntax
The syntax for the 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.
To initialize a new variable created via new
, use the following syntax:
p_var = new(p_place) type(initializer);
where initializer
is the initial value assigned to the new variable, or if type
is of class type, initializer
is the argument(s) to a constructor.
Placement new
can also create an array:
p_var = new(p_place) type [size];
In this case, size
specifies the length of one-dimensional array to create.
When using placement new
, there is often no reason to use the return pointer value. In these cases p_var
is not used and the syntax can be simplfied to one of these:
new(p_place) typename;
new(p_place) type(initializer);
new(p_place) type [size];
Although an object created with the placement new is not normally deleted, it may be neccesary to call its destructor. This is done with the following syntax:
p_var->~type();