C++ functions: ampersand vs asterisk

前端 未结 9 1872
情书的邮戳
情书的邮戳 2020-12-13 03:43

Let\'s say you have a function that modifies a variable.

Should you write it like this: void myfunc(int *a) or like this void myfunc(int &a)

相关标签:
9条回答
  • 2020-12-13 04:38

    I think I would disagre with @bb and @JaredPar and I lean to the opposite side of the fence. After years of trying to support other peoples C++ code, I often find problems lurking in non-obvious side effects of reference arguments. With C#, it is obvious since you have to prefix types of arguments with 'ref'/'out' but references are potentially confusing in C++. So, I like pointers because it's really clear something is coming back up. If you don't like points, C++ is not for you.

    0 讨论(0)
  • 2020-12-13 04:41

    The former forces you to call the function with myfunc(&b) so the caller is aware that b will be modified

    sometimes function could accept const pointer and caller will have wrong thinking that b will be modified.

    My recommendation - prefer use references everywhere where it possible (ofcourse where it needed). In case with function argument - we get benefits:
    - references can't be NULL - it help us to avoid errors and unnecessary asserts or checks.
    - references have only one initialization point and in function boody you always know on what thing input parameter points.

    I'm maintainer on large project. And in either cases I'm looking on function definition before call its. Ofcourse when I looking on function definition I see arguments definition by value, by reference, by const reference or by pointer.

    But it seems like holy-war question, defferent peoples have different view on this point. E.g. google codding convension recomended use pointers in arguments which could be changed and allowed only const references: http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml#Reference_Arguments

    All parameters passed by reference must be labeled const.

    0 讨论(0)
  • 2020-12-13 04:43

    In an ideal world it comes down to whether or not the parameter is an optional output. Do you want to allow the caller to pass NULL if they don't care about it? Then use a pointer. Otherwise a reference is a better choice.

    Note that in both cases the language makes it cumbersome to document an output parameter. It's much better if the whole codebase is const correct, then the users can assume that any non-const reference or pointer parameter is an output.

    0 讨论(0)
提交回复
热议问题