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

后端 未结 9 1580
我寻月下人不归
我寻月下人不归 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:42

    Because references must always be initialized and since they must refer to an existing object, it is much harder (but by no means impossible) to end up with dangling references than it is to have uninitialized/dangling pointers. Also, it's easier to manipulate references because you don't have to worry about taking addresses and dereferencing them.

    But just to show you that a reference by itself doesn't make your program 100% safe, consider this:

    int *p = NULL;
    int &r = *p;
    r = 10; /* bad things will happen here */
    

    Or this:

    int &foo() {
      int i;
      return i;
    }
    
    ...
    
    int &r = foo();
    r = 10; /* again, bad things will happen here */
    

提交回复
热议问题