C、C++函数返回值的细微区别

您所在的位置:网站首页 hsj是啥 C、C++函数返回值的细微区别

C、C++函数返回值的细微区别

2023-01-15 08:42| 来源: 网络整理| 查看: 265

建议:使用指针是最佳原则

C函数返回结构体对象(栈、堆)表现情况: ①返回对象->复制对象 ②返回指针->复制地址

C:

#include #include struct tst{ int age; const char *name; }; /** *返回对象 **/ struct tst get_obj_tst(){ struct tst s = {.age = 18,.name = "hsj is smart!"}; // //旧地址 printf("%p\n",&s); return s; } /** *返回指针 **/ struct tst* get_ptr_tst(){ struct tst* s = (struct tst*)malloc(sizeof(struct tst)); s->age = 18; s->name = "hsj is smart!"; // //旧地址 printf("%p\n",s); return s; } int main(){ { struct tst s = get_obj_tst(); //新地址 printf("%p\n",&s); printf("%d, %s\n",s.age,s.name); } printf("----------------------\n"); { struct tst* sp = get_ptr_tst(); //新地址 printf("%p\n",sp); printf("%d, %s\n",sp->age,sp->name); free(sp); } return 0; }

在这里插入图片描述

C++函数返回结构体对象、类对象(栈、堆)表现情况: ①返回对象->类似引用(同一个地址) ②返回指针->复制地址 ②返回引用->产生碎片,使用[复制构造函数||移动构造函数],原始堆对象有memery_leak内存溢出风险

C++:

#include using namespace std; class demo{ public: demo():num(new int(0)){ cout d.num = NULL; cout int *num = (*this).num; if(num == nullptr){ return -1; } return *num; } void demo::set_num(int new_num){ *((*this).num) = new_num; } /** *返回指针 **/ demo* get_ptr_demo(){ demo* a = new demo(); a->set_num(100); // //旧地址 cout demo* a = new demo(); a->set_num(300); // //旧地址 cout cout struct tst s = {.age = 18,.name = "hsj is smart!"}; // //旧地址 cout demo b = get_obj_demo(); //新地址 cout struct tst* s = get_ptr_tst(); //新地址 cout


【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3