Pointer vs. Reference

What would be better practice when giving a function the original variable to work with:

unsigned long x = 4;

void func1(unsigned long& val) {
     val = 5;            
}
func1(x);

or:

void func2(unsigned long* val) {
     *val = 5;
}
func2(&x);

IOW: Is there any reason to pick one over another?


My rule of thumb is:

Use pointers if you want to do pointer arithmetic with them (eg incrementing the pointer address to step through an array) or if you ever have to pass a NULL-pointer.

Use references otherwise.


I really think you will benefit from establishing the following function calling coding guidelines:

  • As in all other places, always be const -correct.

  • Note: This means, among other things, that only out-values (see item 3) and values passed by value (see item 4) can lack the const specifier.
  • Only pass a value by pointer if the value 0/NULL is a valid input in the current context.

  • Rationale 1: As a caller , you see that whatever you pass in must be in a usable state.

  • Rationale 2: As called , you know that whatever comes in is in a usable state. Hence, no NULL-check or error handling needs to be done for that value.

  • Rationale 3: Rationales 1 and 2 will be compiler enforced. Always catch errors at compile time if you can.

  • If a function argument is an out-value, then pass it by reference.

  • Rationale: We don't want to break item 2...
  • Choose "pass by value" over "pass by const reference" only if the value is a POD (Plain old Datastructure) or small enough (memory-wise) or in other ways cheap enough (time-wise) to copy.

  • Rationale: Avoid unnecessary copies.
  • Note: small enough and cheap enough are not absolute measurables.

  • This ultimately ends up being subjective. The discussion thus far is useful, but I don't think there is a correct or decisive answer to this. A lot will depend on style guidelines and your needs at the time.

    While there are some different capabilities (whether or not something can be NULL) with a pointer, the largest practical difference for an output parameter is purely syntax. Google's C++ Style Guide (https://google.github.io/styleguide/cppguide.html#Reference_Arguments), for example, mandates only pointers for output parameters, and allows only references that are const. The reasoning is one of readability: something with value syntax should not have pointer semantic meaning. I'm not suggesting that this is necessarily right or wrong, but I think the point here is that it's a matter of style, not of correctness.

    链接地址: http://www.djcxy.com/p/20778.html

    上一篇: 何时使用虚拟析构函数?

    下一篇: 指针与参考