Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Explanation of this new() statement

Tags:

c++

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?

like image 696
Homunculus Reticulli Avatar asked Oct 21 '11 09:10

Homunculus Reticulli


People also ask

What is the meaning of new in C++?

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.

What is new operator in C++ give example?

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.

What are the statement in Python?

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.

What does the placement new do?

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.


2 Answers

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();
like image 79
NPE Avatar answered Oct 05 '22 12:10

NPE


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.

like image 33
Nicol Bolas Avatar answered Oct 05 '22 13:10

Nicol Bolas