Explanation of this operator new ()

I am looking at a section of C ++ code, and I came across this block of statements:

static void Vector3DefaultConstructor(Vector3 *self)
{    
    new(self) Vector3();    
}

I did not come to a new operator used this way before. Can someone explain why the new is so called?

+5
source share
3 answers

This is called "placement new." By default, it does not allocate memory, but instead creates an object in this place (here self). However, it may be overloaded for the class.

See the FAQ for more details .

The correct way to destroy an object created using placement newis to call the destructor directly:

obj->~Vector3();
+3
source

- , ?

, . , . new ; .

- ? . , void*, Vector3*. Vector3::Vector3() , , .

+3

: std::vector , push_back.

T*data, data=new T[capacity] - T. , vector , , : , .

, vector::data a void* . , , , .

template <typename T>
void vector <T> :: push_back (const T & value)
{
    resize (m_size + 1);
    // construct a new T in the void buffer.
    new (reinterpret_cast <T*> (m_data) + m_size) T (value);
    ++ m_size;
}

template <typeame T>
void vector <T> :: pop_back ()
{
    (reinterpret_cast <T*> (m_data) + m_size) -> ~ T ();
    -- size;
}
0
source

All Articles