C++ function parameters: use a reference or a pointer (and then dereference)?

后端 未结 11 2230
臣服心动
臣服心动 2021-02-05 10:49

I was given some code in which some of the parameters are pointers, and then the pointers are dereferenced to provide values. I was concerned that the pointer dereferencing wou

11条回答
  •  灰色年华
    2021-02-05 11:21

    There are different guidelines on using reference vs. pointer parameters out there, tailored to different requirements. In my opinion, the most meaningful rule that should be applied in generic C++ development is the following:

    1. Use reference parameters when overloading operators. (In this case you actually have no choice. This is what references were introduced for in the first place.)

    2. Use const-reference for composite (i.e. logically "large") input parameters. I.e input parameters should be passed either by value ("atomic" values) or by const-reference ("aggregate" values). Use pointers for output parameters and input-output parameters. Do not use references for output parameters.

    Taking the above into the account, the overwhelming majority of reference parameters in your program should be const-references. If you have a non-const reference parameter and it is not an operator, consider using a pointer instead.

    Following the above convention, you'll be able to see at the point of the call whether the function might modify one of its arguments: the potentially modified arguments will be passed with explicit & or as already-existing pointers.

    There's another popular rule out there that states that something that can be null should be passed as a pointer, while something that can't be null should be passed as a reference. I can imagine that this might make sense in some very narrow and very specific circumstances, but in general this is a major anti-rule. Just don't do it this way. If you want to express the fact that some pointer must not be null, put a corresponding assertion as the very first line of your function.

    As for the perfromance considerations, there's absolutely no performance difference in passing by pointer or passing by reference. Both kinds of parameters are exactly the same thing at the physical level. Even when the function gets inlined, a modern compiler should be smart enough to preserve the equivalence.

提交回复
热议问题