When to use references vs. pointers

前端 未结 17 2479
一向
一向 2020-11-22 02:27

I understand the syntax and general semantics of pointers versus references, but how should I decide when it is more-or-less appropriate to use references or pointers in an

17条回答
  •  独厮守ぢ
    2020-11-22 03:31

    The following are some guidelines.

    A function uses passed data without modifying it:

    1. If the data object is small, such as a built-in data type or a small structure, pass it by value.

    2. If the data object is an array, use a pointer because that’s your only choice. Make the pointer a pointer to const.

    3. If the data object is a good-sized structure, use a const pointer or a const reference to increase program efficiency.You save the time and space needed to copy a structure or a class design. Make the pointer or reference const.

    4. If the data object is a class object, use a const reference.The semantics of class design often require using a reference, which is the main reason C++ added this feature.Thus, the standard way to pass class object arguments is by reference.

    A function modifies data in the calling function:

    1.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.

    2.If the data object is an array, use your only choice: a pointer.

    3.If the data object is a structure, use a reference or a pointer.

    4.If the data object is a class object, use a reference.

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

提交回复
热议问题