C/C++之函数返回值为指针或者是引用时常见错误总结
【摘要】 1、说明
函数如果是指针或则引用的返回,一般全局变量、局部静态变量、局部动态分配内存的变量可以使用作为函数的返回值,局部变量不行,因为局部变量函数调用完会自动销毁内存,这个时候返回的指针或则引用就有问题了。
2、展示代码
#include <i...
1、说明
函数如果是指针或则引用的返回,一般全局变量、局部静态变量、局部动态分配内存的变量可以使用作为函数的返回值,局部变量不行,因为局部变量函数调用完会自动销毁内存,这个时候返回的指针或则引用就有问题了。
2、展示代码
-
#include <iostream>
-
#include <string.h>
-
#include <stdlib.h>
-
-
using namespace std;
-
-
string& f1(const string &s)
-
{
-
static string result = s;
-
return result;
-
}
-
-
string f2(const string &s)
-
{
-
string result = s;
-
return result;
-
}
-
-
-
string &f3(const string &s)
-
{
-
string *p = new string;
-
*p = s;
-
return *p;
-
}
-
-
int *f4()
-
{
-
int a = 10;
-
return &a;
-
}
-
-
int *f5()
-
{
-
static int a = 10;
-
return &a;
-
}
-
-
int *f6()
-
{
-
int *a = (int *)malloc(sizeof(int) * 10);
-
*a = 10;
-
*(a + 1) = 11;
-
return a;
-
}
-
-
int &f7()
-
{
-
int *a = (int *)malloc(sizeof(int) * 10);
-
*a = 10;
-
*(a + 1) = 11;
-
return *a;
-
}
-
-
int &
文章来源: chenyu.blog.csdn.net,作者:chen.yu,版权归原作者所有,如需转载,请联系作者。
原文链接:chenyu.blog.csdn.net/article/details/64128702
【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱:
cloudbbs@huaweicloud.com
- 点赞
- 收藏
- 关注作者
评论(0)