C++ functions: ampersand vs asterisk

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

    Pointers (ie. the '*') should be used where the passing "NULL" is meaningful. For example, you might use a NULL to represent that a particular object needs to be created, or that a particular action doesn't need to be taken. Or if it ever needs to be called from non-C++ code. (eg. for use in shared libraries)

    eg. The libc function time_t time (time_t *result);

    If result is not NULL, the current time will be stored. But if result is NULL, then no action is taken.

    If the function that you're writing doesn't need to use NULL as a meaningful value then using references (ie. the '&') will probably be less confusing - assuming that is the convention that your project uses.

提交回复
热议问题