I am reviewing a section of C++ code an I came accross this statement block:
static void Vector3DefaultConstructor(Vector3 *self)
{
new(self) Vector3();
}
I have not come accross the new operator being used in this way before. Can someone explain why new is being called in this way?
When new is used to allocate memory for a C++ class object, the object's constructor is called after the memory is allocated. Use the delete operator to deallocate the memory allocated by the new operator.
An Example of allocating array elements using “new” operator is given below: int* myarray = NULL; myarray = new int[10]; Here, new operator allocates 10 continuous elements of type integer to the pointer variable myarray and returns the pointer to the first element of myarray.
Instructions that a Python interpreter can execute are called statements. For example, a = 1 is an assignment statement. if statement, for statement, while statement, etc. are other kinds of statements which will be discussed later.
Placement new is a variation new operator in C++. Normal new operator does two things : (1) Allocates memory (2) Constructs an object in allocated memory. Placement new allows us to separate above two things. In placement new, we can pass a preallocated memory and construct an object in the passed memory.
This is called "placement new
". By default, it does not allocate memory but instead constructs the object at the given location (here, self
). It can, however, be overloaded for a class.
See the FAQ for more info.
The correct way to destroy an object constructed using placement new
is by calling the destructor directly:
obj->~Vector3();
Can someone explain why new is being called in this way?
I can tell you what it does. It effectively calls the constructor on an arbitrary piece of memory, thus constructing the object in that piece of memory. Regular new
both allocates memory and constructs an object in that memory; placement new only does the latter part.
As to why anyone would write that code? No clue. It would make more sense if the object took a void*
rather than a Vector3*
. But unless Vector3::Vector3()
is private, there's no reason to hide the placement new usage inside a static function like this.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With