C++: Why do you need references when you have pointers? [duplicate]

  • Using pointers alone you can’t properly pass-by-reference or return-by-reference.
  • Some methods require a reference. How would you implement a copy-constructor?
  • Sometimes you need to enforce aliasing. You can’t do that with pointers – they can be changed. References cannot bind to something different. So when you initialize a reference, you guarantee it will refer to the same object through its scope.
  • The safety issue
  • (const)References can bind to temporary objects. To create a temporary pointer, you’d need to free it inside the method you pass it to. But you can’t tell if it’s a temporary or not inside.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)