c++ - 为什么没有抓到返回值就没有错误呢?

标签 c++ xcode

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

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

关于c++ - 为什么没有抓到返回值就没有错误呢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18317515/

相关文章:

c++ - float 最大化循环在 D 中不终止,在 C++ 中有效

ios - Xcode 4 - 一键构建到多个设备?

objective-c - 防止键盘 split 并阻止它

xcode - 无法使用 Xcode 10 在 Mojave 上安装 brew

Xcode Workspace 中的 iOS 框架测试失败

ios - Xcode - 无法在脚本中使用 PlistBuddy 修改 plist

c++ - SDL_Mixer 再次播放时,从随机位置开始一段时间然后从头开始

c++ - QTableView强制选择一个单元格

c++ - 我的帧缓冲区有什么问题?

c++ - 如何选择合适的倍数?