C++ functions: ampersand vs asterisk

前端 未结 9 1891
情书的邮戳
情书的邮戳 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: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.

提交回复
热议问题