Reference vs. pointer

前端 未结 6 410
终归单人心
终归单人心 2020-12-28 08:33

What is the difference? Because this:

int Value = 50;
int *pValue = &Value;

*pValue = 88;

and ref version do the same:



        
6条回答
  •  时光说笑
    2020-12-28 09:20

    A pointer is the address of the memory location. You can change the value of that address to point at different memory addresses.

    A reference is an alias of the variable. You can only assign this alias during declaration. You cannot change which variable the reference is an alias of after it's declared.


    The following pointer assignments are not possible with references.

    int a = 10;
    int b = 20;
    
    int* pInt = NULL; // A pointer pointing at nothing.
    pInt = &a; // pInt now points at a
    pInt = &b; // pInt now points at b
    

    As for which one is better, it all depends on context.

    I use references for method and function parameters.

    void updateFoo(Foo& foo)
    

    I use references to alias complex objects.

    Foo& foo = bar.getBaz().getFoo(); // easy access to foo
    

    I use pointers for dynamically allocated objects.

    Foo* pFoo = new Foo();
    

    I use pointers for things which may point at different values (including no value at all).

    Foo* pFoo = NULL;
    
    if (condition1)
        pFoo = &foo1;
    else (condition2)
        pFoo = &foo2;
    

    As a general rule, I default to references and use pointers in places where the limitations on references cause problems.

提交回复
热议问题