Pointer vs. Reference

后端 未结 12 1696
闹比i
闹比i 2020-11-22 11:13

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          


        
12条回答
  •  北恋
    北恋 (楼主)
    2020-11-22 11:32

    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.

提交回复
热议问题