Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ new & delete and string & functions

Okay the previous question was answered clearly, but i found out another problem.

What if I do:

char *test(int ran){ 
    char *ret = new char[ran]; 
    // process... 
    return ret; 
} 

And then run it:

for(int i = 0; i < 100000000; i++){ 
   string str = test(rand()%10000000+10000000); 
   // process... 

   // no need to delete str anymore? string destructor does it for me here?
} 

So after converting the char* to string, I don't have to worry about the deleting anymore?

Edit: As answered, I have to delete[] each new[] call, but on my case its not possible since the pointer got lost, so the question is: how do I convert char to string properly?

like image 736
Newbie Avatar asked Jun 03 '10 13:06

Newbie


1 Answers

Here you are not converting the char* to a [std::]string, but copying the char* to a [std::]string.

As a rule of thumb, for every new there should be a delete.

In this case, you'll need to store a copy of the pointer and delete it when you're done:

char* temp = test(rand()%10000000+10000000);
string str = temp;
delete[] temp;
like image 60
Johnsyweb Avatar answered Sep 22 '22 10:09

Johnsyweb