转载:关于函数返回值的几种情况

来源:互联网 发布:手机移动数据怎么关闭 编辑:程序博客网 时间:2024/05/24 07:43
转自:http://blog.csdn.net/laoyang360/article/details/8169738

关于函数返回值的几种情况  

在一个函数的内部,return的时候返回的都是一个拷贝,不管是变量、对象还是指针都是返回拷贝,但是这个拷贝是浅拷贝。

分为以下几种情况:1)返回一个基本类型的变量;2)返回非动态分配的指针;3)返回动态分配的指针;4)返回非基本类型(对象等)

1.    如果返回一个基本类型的变量,比如:

int a;

a = 5;

return a;

 那么就会a的一个拷贝,即5返回,然后a就被销毁了。尽管a被销毁了,但它的副本5还是成功地返回了,所以这样做没有问题。

 

2.   但是对于非动态分配(new/malloc)得到的指针,像1那么做就会有问题,比如在某个函数内部:

int a[] = {1, 2};

return a;

那么也会返回指针a的一个拷贝,我们假定a的地址值为0x002345FC,那么这个0x2345FC是能够成功返回的。当return执行完成后,a就要被销毁,也就是0x002345FC所指向的内存被回收了。如果这时候在函数外面,去地址0x002345FC取值,那得到的结果肯定是不对的。这就是为什么不能返回局部指针的原因。返回局部变量的引用的道理和这个类似。注意:不能返回局部变量的指针或引用! 

      注意:《高质量程序设计指南中C++/C语言》中指出:return语句不可返回堆栈内存的指针或者引用因为该内存单元在函数体结束时就被自动释放

强调举例一下,看下面的程序:

 

[cpp] view plain copy
print?
  1. #include<iostream>  
  2. using namespace std;  
  3. char *GetMemory(void)    // char *GetMemory(char *p,int num)  
  4.   
  5. {  
  6. char p[ ] = “hello world”// p= (char *)malloc(sizeof(char) *num);  
  7. return p;   
  8. }  
  9.   
  10. int main ()  
  11. {  
  12.        char *str = NULL;  
  13.        str = GetMemory() ; //str = GetMemory(str,100) ;  
  14.        cout << str ;  
  15.     return 0;  
  16. }  
#include<iostream>using namespace std;char *GetMemory(void)    // char *GetMemory(char *p,int num){char p[ ] = "hello world"; // p= (char *)malloc(sizeof(char) *num);return p; }int main (){       char *str = NULL;       str = GetMemory() ; //str = GetMemory(str,100) ;       cout << str ;    return 0;}

答案,可能是乱码,也可能是正常输出。因为GetMemory返回的是指向栈内存的指针,该指针的地址不是NULL,但其原来的内容已经被清除,新内容不可知。

为什么不是输出的是数组的首地址呢??如果函数是黑体部分的话,可以利用函数返回值来传递动态内存。那是因为注释部分是堆操作,不是会被os自动释放的栈内存。

但是若用非黑体的部分怎么就不行了呢?栈内存就是编译器自动支配的,也就是说非动态分配的东西基本上都在栈中

这些问题可以用下面的例子回答:

 

[cpp] view plain copy
print?
  1. int testA (void)   
  2. {   
  3.   
  4. int b = 1 ;   
  5.   
  6. return b ;   
  7.   
  8. }  
  9.   
  10. char * testB (void)   
  11. {   
  12.   
  13. char str[] = “abc” ;   
  14.   
  15. return str ; //但这样的方法是不推荐的  
  16.   
  17. }   
  18.   
  19. int main()   
  20.   
  21. {   
  22.   
  23. printf( ” the value of testA is %d \n”, testA() ) ;   
  24.   
  25. printf( ” the value of testB is %c ”, *( testB() ) ) ;    
  26.   
  27. }   
int testA (void) { int b = 1 ; return b ; }char * testB (void) { char str[] = "abc" ; return str ; //但这样的方法是不推荐的} int main() { printf( " the value of testA is %d \n", testA() ) ; printf( " the value of testB is %c ", *( testB() ) ) ;  } 


对于返回值的情况:

testAmain函数同在栈区,testA结束时C++创建临时变量,然后将返回值复制给该临时变量。printf( ” the value of testA is %d \n”, testA() ) 输出的是该临时变量的值testA中的b已经不存在。

对于返回指针的情况:这是最复杂的部分。首先,对于上面的情形:返回一个数组的首地址,由于是返回char *类型,所以C++会首先创建一个char *类型的临时变量,再把该数组的首地址赋给临时变量;函数结束后该数组也就被销毁,这就意味着临时变量指向了一个未声明的地址幸运的情况下,这段内存暂时还没有被其他的数据所覆盖,因此还能输出正确的内容。在testB里面,如果换成char* str=”abc”;return str; 由于这时str指向的是全局数据区的一段内存地址,所以函数结束后临时变量也指向该地址,所以编译器不会提出警告。但这样的方法是不推荐的

返回引用:这中情况的效率最高,它直接返回一个对象,不产生返回值的副本。但同时也要注意避免返回局部引用的情况。

 

3.  对于返回(动态分配得到的)指针的另外一种情况,比如在函数内部:

int a = new int(5);

return a;

这样做是可以的。return a执行完后,a并没有被销毁(必须要用delete才能销毁a),所以这里返回的a是有效的。

 

4.    如果不是基本数据类型,比如:

class A

{

public:

               OtherClass * …

};

 

如果在某个函数内部有一个A类的局部变量,比如:

A a;

return a;

这时候也会返回a的一个拷贝,如果A没有写深拷贝构造函数,就会调用缺省的拷贝构造函数(浅拷贝),这样做就会失败的

如果A中提供了深拷贝构造函数,则这样做就是可以的。

 

实验代码如下:

[cpp] view plain copy
print?
  1. #include <iostream>  
  2. using namespace std;  
  3. int some_fun1()  
  4. {  
  5.        cout << ”\nsome_fun1()…” << endl;  
  6.        int a = 5;  
  7.        return a;                   //OK  
  8. }  
  9.   
  10.    
  11.   
  12. int* some_fun2()  
  13. {  
  14.        cout << ”\nsome_fun2()…” << endl;  
  15.        int a = 5;  
  16.        int *b = &a;  
  17.        return b;                   // not OK  
  18. }  
  19.   
  20.    
  21.   
  22. int* some_fun3()  
  23. {  
  24.   
  25.        cout << ”\nsome_fun3()…” << endl;  
  26.        int *c = new int(5);  
  27.        return c;                   // OK, return c执行完后,并没被销毁(必须要用delete才能销毁)  
  28.   
  29. }  
  30.   
  31.    
  32.   
  33. class CSomething  
  34. {  
  35. public:  
  36.       int a;  
  37.        int b;  
  38.  public:  
  39.   
  40.        CSomething(int a, int b)  
  41.        {  
  42.               this->a = a;    
  43.               this->b = b;  
  44.        }  
  45. };  
  46.   
  47.    
  48.   
  49. class CA  
  50. {  
  51. public:  
  52.        CA(CSomething* sth)  
  53.        {  
  54.               this->sth = new CSomething(sth->a, sth->b);  
  55.        }  
  56.   
  57.        // 如果不实现深拷贝,请注释这个拷贝构造函数  
  58.        CA(CA& obj)  
  59.        {  
  60.               sth = new CSomething((obj.sth)->a, (obj.sth)->b);  
  61.        }  
  62.        ~CA()  
  63.        {  
  64.               cout << ”In the destructor of class CA…” << endl;  
  65.              if (NULL != sth)   
  66.               {  
  67.                      delete sth;  
  68.               }  
  69.        }  
  70.   
  71.         void Show()  
  72.        {  
  73.               cout << ”(“ << sth->a << “, ” << sth->b << “)” << endl;  
  74.        }  
  75.   
  76.       void setValue(int a, int b)  
  77.       {  
  78.               sth->a = a;   
  79.               sth->b = b;  
  80.        }  
  81.   
  82.        void getSthAddress()  
  83.        {  
  84.               cout << sth << endl;  
  85.        }  
  86.    
  87. private:  
  88.        CSomething* sth;            // 以指针形式存在的成员变量  
  89.   
  90. };  
  91.   
  92. CA some_fun4()  
  93. {  
  94.        cout << ”\nsome_fun4()…” << endl;  
  95.        CSomething c(1, 2);  
  96.        CA a(&c);  
  97.        cout << ”\\ some_fun4()…” << endl;  
  98.        return a;                       // 如果CA没有实现深拷贝,则not OK;如果实现深拷贝,则OK   
  99.   
  100. }  
  101.   
  102.   
  103. int main(int argc, char* argv[])  
  104. {  
  105.   
  106.        int a = some_fun1();  
  107.        cout << a << endl;              // OK   
  108.   
  109.        int *b = some_fun2();  
  110.        cout << *b << endl;             // not OK,即便返回结果正确,也不过是运气好而已  
  111.   
  112.         int *c = some_fun3();           // OK, return c执行完后,c并没有被销毁(必须要用delete才能销毁)  
  113.         cout << *c << endl;  
  114.        delete c;  
  115.   
  116.        CA d = some_fun4();           // 如果CA没有实现深拷贝,则not OK;如果实现深拷贝,则OK  
  117.        d.Show();  
  118.   
  119.        return 0;  
  120.   
  121. }   
  122. <img src=”http://img.my.csdn.net/uploads/201211/10/1352544421_7259.jpg” alt=“”>  
#include <iostream>using namespace std;int some_fun1(){       cout << "\nsome_fun1()..." << endl;       int a = 5;       return a;                   //OK}int* some_fun2(){       cout << "\nsome_fun2()..." << endl;       int a = 5;       int *b = &a;       return b;                   // not OK}int* some_fun3(){       cout << "\nsome_fun3()..." << endl;       int *c = new int(5);       return c;                   // OK, return c执行完后,并没被销毁(必须要用delete才能销毁)}class CSomething{public:      int a;       int b; public:       CSomething(int a, int b)       {              this->a = a;                this->b = b;       }};class CA{public:       CA(CSomething* sth)       {              this->sth = new CSomething(sth->a, sth->b);       }       // 如果不实现深拷贝,请注释这个拷贝构造函数       CA(CA& obj)       {              sth = new CSomething((obj.sth)->a, (obj.sth)->b);       }       ~CA()       {              cout << "In the destructor of class CA..." << endl;             if (NULL != sth)               {                     delete sth;              }       }        void Show()       {              cout << "(" << sth->a << ", " << sth->b << ")" << endl;       }      void setValue(int a, int b)      {              sth->a = a;               sth->b = b;       }       void getSthAddress()       {              cout << sth << endl;       }private:       CSomething* sth;            // 以指针形式存在的成员变量};CA some_fun4(){       cout << "\nsome_fun4()..." << endl;       CSomething c(1, 2);       CA a(&c);       cout << "\\ some_fun4()..." << endl;       return a;                       // 如果CA没有实现深拷贝,则not OK;如果实现深拷贝,则OK }int main(int argc, char* argv[]){       int a = some_fun1();       cout << a << endl;              // OK        int *b = some_fun2();       cout << *b << endl;             // not OK,即便返回结果正确,也不过是运气好而已        int *c = some_fun3();           // OK, return c执行完后,c并没有被销毁(必须要用delete才能销毁)        cout << *c << endl;       delete c;       CA d = some_fun4();           // 如果CA没有实现深拷贝,则not OK;如果实现深拷贝,则OK       d.Show();       return 0;} 

          参考了网上部分资源!

 

0 0
原创粉丝点击