Dynamic Memory and Arrays
I am attempting to work on dynamic memory allocation and I thought trying to make a simplified vector class would be good practice. The only functions I am going to implement will be push, pop, isEmpty, clear, and size. It only works with string objects right now because I have never done templated classes. That's what I would need to allow a class to work on different objects right? I know function templates so I figured templated classes would be only a slight extension.
Anyway, now that I have gone off-topic in my OP to get back, I have been having trouble with my push method. Here is the pertinent code, but I will attach everything in case you want to see.
void myVector::push_back(std::string temp)
//temporary array one bigger than the old array
std::string *tempArr = new std::string[count + 1];
//loop over every element and copy all of the original array to the bigger
//array. count is number of items currently in vector
for(int i = 0; i < count; i++)
tempArr[i] = arr[i];
//add the new element to the back of the new array
tempArr[count] = temp;
//set the new array to be this vectors container
arr = tempArr;
//loop over every element and print everything out for debugging
for(int i = 0; i <= count; i++)
std::cout<<"value at: arr["<<i<<"] is: "<<arr[i]<<std::endl;
//increase the number of elements
If I leave the comment on the delete tempArr it works, but with it in there it doesn't. To me, it makes sense that you should have to have it there otherwise won't you get memory leaks as every time you are adding elements you are never freeing up the memory you just allocated. It seems to work though albeit not as efficient as it could be without the memory leak. I think the problem is the line where I set arr= tempArr because now they are pointing to each other so deleting tempArr also deletes the other.
What say you?