C++ functions: ampersand vs asterisk

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

    One difference, like has been mentioned before, is you can't pass a null reference, but you can pass a null pointer.

    Another thing, also mentioned already, when you call f(a,b) there could be confusion if the caller doesn't know that f could potentially change the value for b

    However, yet another issue, which is rather subtle, but I still ran into it, is the semantics of references.

    Pointers are passed by value, but references are not.

    Which means, if you pass a parameter by pointer, you can change the pointer and make it point to something else.

    Consider this:

    void f1_ptr( type * a )
    {
        a = new type(); //no change to passed parameters, you're changing the pointer which was passed by value
    }
    
    void f2_ptr( type * a )
    {
        *a = some_other_value; //now you're changing the value of the parameter that was passed
    
       //or, if type is a class or struct:
    
       a->some_method_that_modifies_object(); //again, changing the parameter that was passed
    }
    

    But, when passing by reference, you can't change the reference to refer to another value. Once the reference is set, it can't be changed.

    void f3_ref( type& a )
    {
        a = type(); //the referred variable has also changed
    }
    
    //....
    
    type obj = type( params );
    
    f3_ref( obj ); //obj now changed
    
    f1_ptr( &obj ); //obj doesn't change
    
    f2_ptr( &obj ); //obj now changed
    

提交回复
热议问题