I'm reading the book "Programming Principle and Practices using C++" by the author of the language.
I'm reading the part where the book basically describes how to implement std::vector. And here's a piece of code in the book:
template<typename T, typename A = std::allocator<T>> class vector {
A alloc;
int space, size;
T* elem;
//...some code
reserve(int newalloc) {
if (newalloc <= space) return; // never decrease allocation
T* p = alloc.allocate(newalloc); // allocate new space
for (int i = 0; i < sz; ++i) alloc.construct(&p[i], elem[i]); // copy
for (int i = 0; i < sz; ++i) alloc.destroy(&elem[i]); // destroy
alloc.deallocate(elem, space); // deallocate old space
elem = p;
space = newalloc;
}
};
The book mentions that we have to use std::allocator because the vector's data structure consists of some initialized data and some uninitialized data.
I'm not clear what that means. What could go wrong if I use new and delete?
template<typename T> class vector2 {
A alloc;
int space, size;
T* elem;
//some code
reserve(int newalloc) {
if (newalloc <= space) return;
T* p = new T[newallow];
for (int i = 0; i < sz; ++i) p[i] = elem[i];
delete[] elem;
elem = p;
space = newalloc;
}
};