C++ return


  • 一般情況下,返回類型是 void 的函數使用 return 語句是為了引起函數的強制結束,這種 return 的用法類似於循環結構中的 break 語句(第 6.10 節)的作用
  • 1 //cstdlib 頭文件定義了兩個預處理變量,分別用於表示程序運行成功和失敗:
    2 #include <cstdlib>
    3 int main()
    4 {
    5 if (some_failure)
    6 return EXIT_FAILURE;
    7 else
    8 return EXIT_SUCCESS;
    9 }
  • 函數的返回值用於初始化調用函數處創建的臨時對象。在求解表達式時,如果需要一個地方儲存其運算結果,編譯器會創建一個沒有命名的對象,這就是臨時對象。 在英語中, C++ 程序員通常用 temporary 這個術語來代替 temporary object
  • 1 // return plural version of word if ctr isn't 1
    2 string make_plural(size_t ctr, const string &word,
    3 const string &ending)
    4 {
    5 return (ctr == 1) ? word : word + ending;
    6 }
    /*我們可以使用這樣的函數來輸出單詞的單數或復數形式。這個函數要么返回其形參 word 的副本
    要么返回一個未命名的臨時string 對象,這個臨時對象是由字符串 word 和 ending 的相加而產生的
    這兩種情況下,return 都在調用該函數的地方復制了返回的 string 對象。
    */
  • 當返回值是引用類型時,調用函數返回結果時返回的時候沒有進行復制
    1 // find longer of two strings
    2 const string &shorterString(const string &s1, const string &s2)
    3 {
    4 return s1.size() < s2.size() ? s1 : s2;
    5 }

     

  • 千萬不能返回局部變量的引用,當函數執行完后,局部變量的存儲空間會被釋放,對局部對象的引用就會指向不確定的內存
     1 #include<iostream>
     2 using namespace std;
     3 int& func()
     4 {
     5     int a = 55;
     6     cout << "函數里面a的地址:" << &a<<endl;
     7     return a;
     8 }
     9 int main()
    10 {
    11     int c = func();
    12     cout << "函數返回值地址:"<< &c <<endl;
    13     cout << c;
    14     return 0;
    15 }

    //以上情況c的值為55,地址變了
    可見這樣接收返回的局部變量的引用可以把它的值保留下來

  •  

     1 #include <iostream>
     2 using namespace std;
     3 int &c()
     4 {
     5     int a=5;
     6     cout <<&a <<endl;
     7     return a;
     8 }
     9 int main()
    10 {
    11     int *b;
    12     b = &c();
    13     cout << b << endl;
    14     cout << *b << endl;//如果是cout << b << *b << endl; 又會發現*b==5?
    15     return 0;
    16 }

    內存被釋放

  •  不要返回局部變量的指針

     1 #include <iostream>
     2 using namespace std;
     3 int *c()
     4 {
     5     int a=5;
     6     cout <<&a <<endl;
     7     return &a;
     8 }
     9 int main()
    10 {
    11     int *b = c();
    12     cout << *b <<  endl << b << endl;
    13     cout << *b << endl;
    14     return 0;
    15 }



    第一次輸出的時候*b是函數局部變量原來的值

    如果第一次輸出地址,后面輸出*b是位置的

     


     在輸出前先輸出一個無關的變量(a),后面又指向未知了,所以說出現上面的情況
    應該是因為函數執行完后輸出的返回值的時候局部變量還沒有來得及釋放


    嘗試用一個變量將還沒有釋放的內存里的值保存下來

  •  

     1 #include <iostream>
     2 using namespace std;
     3 int &get(int *arry, int index) { return
     4 arry[index]; }
     5 int main() {
     6     int ia[10];
     7     for (int i = 0; i != 10; ++i)
     8     {
     9         get(ia, i) = 2;
    10         cout << ia[i];
    11     }
    12 }


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM