Difference between const. pointer and reference?

后端 未结 5 1031
滥情空心
滥情空心 2020-11-30 19:43

What is the difference between a constant pointer and a reference?

Constant pointer as the name implies can not be bound again. Same is the case with the reference.

5条回答
  •  一整个雨季
    2020-11-30 20:12

    When you should use each:

    reference: Use these by default. It is very common for people to dereference NULL pointers. You eliminate that risk with a reference.

    const pointer: When you want a reference, but can't make one. For example, you are writing a driver, and you'd like a pointer to the beginning of a memory map. A reference doesn't make as much sense in that case. Also, if you need an array of the things, a reference won't work (though an array of simple classes with reference members will).

    In the next example, a const pointer checks an error that a reference can't check:

    int addFour( int* register ){
      if(isNull(arg)){
        throw NullPointerException();
      }  
    
      // some stuff
      *register += 4;
    
      return register;
    }
    
    // This could be any function that does pointer math.
    bool isNull(const int* ptr){
      return( NULL == ptr );
    }
    

提交回复
热议问题