2013-08-19 95 views
1

据我所知,从返回类型函数接收到的值必须存储在被调用的地方,否则它是错误的。请解释下面的代码如何正常工作。返回值没有捕获时为什么没有错误?

#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++。

谢谢。

+6

你的假设是错误的。您可能随时丢弃函数的返回值,例如,如果您不关心函数是否成功。在你的情况下,你当然会泄漏内存,但像valgrind这样的工具会告诉你这一点。 – arne

+2

...在C++中,您可以使用智能指针,即使您忽略返回的对象(本例为C++ 11 std :: unique_ptr ),也可以确保不泄漏, –

回答

6

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

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

一般来说,如果你正在编写C++,不要编写C语言。

+5

+1,I'如果我可以:*不要写C如果你正在编写C++ * –

+2

*“如果你正在编写C++,不要写C”*我想在大多数常见的前额中纹身自称***的人“C++程序员”***。 C-with-classes可以追溯到80年代末期,但是大多数时候,当我阅读其他人的C++代码时,我觉得如果我和我的朋友Doc和Marty一起驾驶DeLorean。 – Manu343726

相关问题