Memory Allocation In A String Class
I'm trying to make my own string class. I wrote a member function to append to a string, but I'm not sure if its very good.
First off at the start of the code I make a pointer that points to the existing string. Then I make a new string, of the combined size. Then I copy the contents of the original, then the string to add to the new string.
I got 2 questions here. First is: Will the memory stored at 'origin' be freed when it goes out of scope?
Also instead of making a new string of the combined size, is it possible to resize the amount of space allocated to 'str_ptr' whilst retianing its original slot in memory? That way I wouldent have to copy its existing contents over. Or could that cause problems with whatevers stored next to it? Anyway heres my function:
str_ptr and size are class variables.
void String::Add(char *add)
char *origin = str_ptr;
//Get New Size And Resize String
char *tmp = add;
str_ptr = new char[size];
char *ptr = str_ptr;
while(*origin) *ptr=*origin, origin++, ptr++; //Copy original string
while(*add) *ptr = *add, ptr++, add++; //Copy string to append