C++ new&delete和string&functions

New*_*bie 6 c++ string char new-operator delete-operator

好的,上一个问题得到了清楚的回答,但我发现了另一个问题.

如果我这样做:

char *test(int ran){ 
    char *ret = new char[ran]; 
    // process... 
    return ret; 
} 
Run Code Online (Sandbox Code Playgroud)

然后运行它:

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?
} 
Run Code Online (Sandbox Code Playgroud)

所以在将char*转换为字符串之后,我不必再担心删除了吗?

编辑:作为回答,我必须delete[]每次new[]调用,但在我的情况下,由于指针丢失,它不可能,所以问题是:如何正确地将char转换为字符串?

Joh*_*web 9

在这里你是不是转换char*一个[std::]string,但复制char*一个[std::]string.

根据经验,每一个new应该有一个delete.

在这种情况下,您需要在完成后存储指针的副本delete:

char* temp = test(rand()%10000000+10000000);
string str = temp;
delete[] temp;
Run Code Online (Sandbox Code Playgroud)

  • 是的,你可以做一些像`return string(ran,'a')`.看一下字符串构造函数http://www.cplusplus.com/reference/string/string/string/ (3认同)