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.

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 13,601评论 0 23
  • 转眼已经快二十天过去了 感觉自己是有了一点进步 但是还不够啊。不能够光顾着补基础 还是先熟练使用安卓的各种内建控件...
    观察者_王动阅读 1,018评论 0 0
  • 财富目标:3月到5月,每月收入港币5万 1. 每月给爸爸三千块,希望他开开心心,身体健康。 2. 每月给张健发起的...
    潔雯阅读 1,468评论 0 3
  • 原来80年代末,我的家乡有条大河,水很清澈。我大姑父每个礼拜有几天早起去ban鱼,这个ban不知道怎么写,解释一下...
    飞鱼说说阅读 1,553评论 0 0
  • 一个平常的下午, 我在租开来的房子。 整天的雨没法出门。 漂泊不定的游子,不知道要上哪去玩,一个人始终就是一个人。...
    风吹落雪阅读 1,724评论 1 0

友情链接更多精彩内容