Why is a c++ reference considered safer than a pointer?

后端 未结 9 1523
我寻月下人不归
我寻月下人不归 2020-12-03 18:23

When the c++ compiler generates very similar assembler code for a reference and pointer, why is using references preferred (and considered safer) compared to pointers?

相关标签:
9条回答
  • 2020-12-03 18:58

    A pointer is an independent variable that can be reassigned to point to another date item, unintialized memory, or just no where at all (NULL). A pointer can be incremented, decremented, subtracted from another pointer of the same type, etc. A reference is tied to an existing variable and is simply an alias for the variable name.

    0 讨论(0)
  • 2020-12-03 19:00

    A reference is always initialized from an existing object, thus it can never be NULL, whereas a pointer variable is allowed to be NULL.

    EDIT: Thanks for all of the replies. Yes, a reference can indeed point to garbage, I forgot about dangling references.

    0 讨论(0)
  • 2020-12-03 19:00

    Well the answer you point out answer that. From the "safer" point of view I think that basically it is hard to write code like :

    int* i;
    // ...
    cout << *i << endl; // segfault
    

    As a reference is always initialized, and

    MyObject* po = new MyObject(foo);
    // ...
    delete po;
    // ...
    po->doSomething(); // segfault
    

    But as said in the question you mention, that's not only because they are safer that references are used ...

    my2c

    0 讨论(0)
提交回复
热议问题