C/C++之函数返回值为指针或者是引用时常见错误总结

1、说明

       函数如果是指针或则引用的返回,一般全局变量、局部静态变量、局部动态分配内存的变量可以使用作为函数的返回值,局部变量不行,因为局部变量函数调用完会自动销毁内存,这个时候返回的指针或则引用就有问题了。



2、展示代码

#include 
#include 
#include 

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 &f8()
{
   int a = 10;
   return a;
}
int main()
{
    cout<<"hello word"<

你可能感兴趣的:(C&C++)