C++ functions: ampersand vs asterisk

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

    I like passing by reference if NULL does not have significance, but I can see the arguments for both. If you're careful about coding you could probably eliminate the accidental pass-by-reference objection by making sure you always pass your variables by const reference, eg:

    myfunc( const_cast< const int& >( a ) );
    
    // Alternatively, this approach may require additional handling 
    // in the function, but it's cleaner at call point
    myfunc( boost::cref( a ) );
    

    That's a lot of extra code for little benefit, though. As Kenny pointed out, C# addressed this from the opposite end (requiring specific passing by reference), but that's not an option for C++ (unless, for example, you wrote your functions to take a reference wrapper as their parameter, like boost::ref(param)), eg:

    void myfunc( const boost::reference_wrapper< int >& a ) { ... }
    

    Fixing the pointer problem is more problematic, though... there's no compile-time way to ensure the pointer is valid, so you end up with either run time problems for pointer issues, or run time checks, or both. Tis the nature of pointers.

    Anyway, that's just my opinion, for what it's worth.

提交回复
热议问题