c ++问题中的内存释放(Visual Studio 2010)

Ita*_*aro -1 c++ memory-management

我正在尝试学习C++,在这个过程中我试图编写一个函数,它获取两个char指针并将第二个连接到第一个(我知道有strcat这个).
但是 - 我想要完成的是修改第一个参数指针,使其指向结果.因此我在第一个参数中使用了对指针的引用.

在从函数返回之前我想释放第一个参数内存,但是我收到一个错误.

这是代码:

void str_cat(char*& str1, char* str2)
{
 if (!str1)
 {
  str1 = str2;
  return;
 }
 if (!str2)
  return;
 char * new_data = new char[strlen(str1) + strlen(str2) +1];
 char * new_data_index = new_data;
 char * str1_index = str1;
 char * str2_index = str2;

 while(*str1_index)
  *new_data_index++ = *str1_index++;
 while(*str2_index)
  *new_data_index++ = *str2_index++;
 *new_data_index = NULL;

 delete str1; //ERROR HERE (I also tried delete[] str1)

 str1 = new_data;
}
Run Code Online (Sandbox Code Playgroud)

我不懂为什么.
有什么建议?

谢谢,
Itay \

编辑 以下是我如何使用该功能

char * str1 = NULL;
char * str2 = NULL;
str_cat(str1, "abc");
str_cat(str2, "def");
str_cat(str1, str2);
Run Code Online (Sandbox Code Playgroud)

小智 7

您只能删除使用new分配的内容 - 如果您的代码如下所示:

str_cat( "foo", "bar" );
Run Code Online (Sandbox Code Playgroud)

这将是非法的.基本上,您的功能完全不安全.更好的设计是通过函数的返回值返回新字符串.更好的是,忘记整个想法并使用std :: string.

虽然学习使用对指针的引用是一件值得称赞的事情,但你应该知道它们在C++编程中很少使用.建议您花时间学习使用C++标准库的功能.