为什么没有捕获返回值时没有错误

Why is there no error when the return value is not catched?

本文关键字:有错误 返回值 为什么      更新时间:2023-10-16

据我所知,从返回类型函数接收到的值必须存储在调用它的位置,否则就会出错。请解释下面的代码是如何正常工作的。

#include <iostream>
#include <stdlib.h>
#include<assert.h>
//Returns a pointer to the heap memory location which  stores the duplicate string
char* StringCopy(char* string) 
{                              
    long length=strlen(string) +1;
    char *newString;
    newString=(char*)malloc(sizeof(char)*length);
    assert(newString!=NULL);
    strcpy(newString,string);
    return(newString);
}
int main(int argc, const char * argv[])
{
    char name[30]="Kunal Shrivastava";
    StringCopy(name);   /* There is no error even when there is no pointer which 
                           stores the returned pointer value from the function 
                           StringCopy */
    return 0;
}

我在Xcode中使用c++。

谢谢。

在C++中不需要使用函数调用(或任何其他表达式)的结果。

如果您想避免由于返回一个指向动态内存的哑指针并希望调用方记得释放它而可能导致的内存泄漏,那么不要这样做。返回一个RAII类型,它将自动为您清理任何动态资源。在这种情况下,std::string将是理想的;甚至不需要编写函数,因为它有一个合适的构造函数。

一般来说,如果你在写C++,就不要写C。