When to Use Reference Arguments

C++ Primer Plus

There are two main reasons for using reference arguments:

  • To allow you to alter a data object in the calling function
  • To speed up a program by passing a reference instead of an entire data object

The second reason is most important for larger data objects, such as structures and classobjects.These two reasons are the same reasons you might have for using a pointer argu-ment.This makes sense because reference arguments are really just a different interface for
pointer-based code. So when should you use a reference? Use a pointer? Pass by value?The following are some guidelines.

A function uses passed data without modifying it:

  • If the data object is small, such as a built-in data type or a small structure, pass itby value.
  • If the data object is an array, use a pointer because that’s your only choice. Make thepointer a pointer to const.
  • If the data object is a good-sized structure, use a const pointer or a const referenceto increase program efficiency.You save the time and space needed to copy a struc-ture or a class design. Make the pointer or reference const.
  • If the data object is a class object, use a const reference.The semantics of classdesign often require using a reference, which is the main reason C++ added thisfeature.Thus, the standard way to pass class object arguments is by reference.

A function modifies data in the calling function:

  • If the data object is a built-in data type, use a pointer. If you spot code like
    fixit(&x), where x is an int, it’s pretty clear that this function intends to modify x.
  • If the data object is an array, use your only choice: a pointer.
  • If the data object is a structure, use a reference or a pointer.
  • If the data object is a class object, use a reference.

Of course, these are just guidelines, and there might be reasons for making differentchoices. For example, cin uses references for basic types so that you can use cin >> ninstead of cin >> &n.

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • **2014真題Directions:Read the following text. Choose the be...
    又是夜半驚坐起閱讀 11,089評論 0 23
  • 轉(zhuǎn)眼已經(jīng)快二十天過去了 感覺自己是有了一點進(jìn)步 但是還不夠啊。不能夠光顧著補(bǔ)基礎(chǔ) 還是先熟練使用安卓的各種內(nèi)建控件...
    觀察者_(dá)王動閱讀 108評論 0 0
  • 財富目標(biāo):3月到5月,每月收入港幣5萬 1. 每月給爸爸三千塊,希望他開開心心,身體健康。 2. 每月給張健發(fā)起的...
    潔雯閱讀 210評論 0 3
  • 原來80年代末,我的家鄉(xiāng)有條大河,水很清澈。我大姑父每個禮拜有幾天早起去ban魚,這個ban不知道怎么寫,解釋一下...
    飛魚說說閱讀 226評論 0 0
  • 一個平常的下午, 我在租開來的房子。 整天的雨沒法出門。 漂泊不定的游子,不知道要上哪去玩,一個人始終就是一個人。...
    風(fēng)吹落雪閱讀 262評論 1 0

友情鏈接更多精彩內(nèi)容