1

I've recently read about placement new and i would like to use it in one of my assignments. I am not allowed to use the stl containers so i would like to make a vector like container. So lets say i preallocate 10 slots in an array to store my objects and then the user adds 11 items. How could i use placement new to store the first 10 objects just by copying them into the array and then initialize a new object and add it into the vector?

The current code i am using for the extra allocation space is this:

template <class T>
void Vector<T>::allocMem(int objects)
{
    T *_new_data = new T[2*capacity];

    for(int i = 0; i < size(); i++)
    {
        _new_data[i] = _data[i];
    }

    delete [] _data;

    _data = _new_data;

    capacity = 2*capacity;
}

And in the place of that i would like to add the use of placement new.

1 Answers1

1
T *_new_data = (T*)new char[sizeof(T)*2*capacity];

for(int i = 0; i < size(); i++)
{
    new (_new_data + i) T(_data[i]);
}

See also C++ placement new

Community
  • 1
  • 1
jmihalicza
  • 2,083
  • 12
  • 20