I know that the delete p works, but I cannot visualize what is happening. I changed it to delete[] p because I think the memory elements should be delete to prevent a memory leak but that crashes. Please explain what is going on.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
#include "std_lib_facilities.h"
int main()
{
vector<double>* p = new vector<double>(10);
int n = 0;
for (double d; cin >> d;) {
if (n == p->size()) {
vector<double>* q = new vector<double>(p->size() * 2);
copy(p->begin(), p->end(), q->begin());
delete p; // <-- Please explain to me what this does. I see this
// as deleting the pointer value but what about the
// elements the pointer points to.
p = q;
}
(*p)[n] = d;
++n;
}
}
delete[] is only used to delete arrays, which are allocated with new type[size]. p points to an std::vector<double> which is a single object. The fact that this particular type implements a sequence type that can hold multiple objects is of no concern to you. This detail is dealt with by the std::vector implementation.
Rule of thumb: new type[size] has to be matched with a delete[], and new type has to be matched with a delete.