30

Possible Duplicate:
C++: When to use References vs. Pointers
Could operator overloading have worked without references?

I couldn't help it, but this fundamental question was on my mind: why does C++ have references when you could do with pointers just as well?

I know that in certain situations they are slightly safer and more often than not they make the code prettier, but technically there is no difference, right? So are there any situations where I couldn't do with a pointer and a reference is a must?
I would like to see specific examples of when using references is unavoidable.

Disclaimer:
I haven't found any answers to this on StackOverflow, this is not a question about the differences in syntax. I am wondering why the C++ language introduced references in the first place.

Community
  • 1
  • 1
Eitan T
  • 32,660
  • 14
  • 72
  • 109
  • 1
    I don't think there are any situations where references are *unavoidable*. After all, people have been writing C programs - which only have pointers - long before C++ existed. – HighCommander4 May 28 '12 at 08:41
  • References are not unavoidable (after all it's just syntax). The point is they're **much more** safer than pointers, not just _slightly safer_. No I'm wrong: much much much much more safer. If the price to pay is some subtle situation where they can be _dangerous_ then...OK, at least we saved 99% of our bugs related to pointers usage. – Adriano Repetti May 28 '12 at 08:41
  • 6
    You misspelled `Why do you need pointers when you have references?` – Luchian Grigore May 28 '12 at 08:42
  • 1
    @Thilo I was actually wondering why the C++ language introduced references in the first place. The duplicate you proposed does not answer my question. – Eitan T May 28 '12 at 08:43
  • @LuchianGrigore LOL :) But sometimes you couldn't go about with references, right? For instance, when you need lazy initialization. – Eitan T May 28 '12 at 08:45
  • @EitanT: Yeah, it is kind of the opposite: The accepted answer there says "use pointers only when you must, otherwise references are better". – Thilo May 28 '12 at 08:45
  • 3
    The historical reason is that references make operator overloading look much nicer, you can write `X + Y` instead of `*pX + *pY`. See [Why does C++ have both pointers and references?](http://www.research.att.com/~bs/bs_faq2.html#pointers-and-references) – Bo Persson May 28 '12 at 08:45
  • @Bo Persson actually according to the proposed answers, you couldn't do operator overloading _at all_ without references. – Eitan T May 28 '12 at 08:47
  • Interesting debate here for further reading: http://www.cplusplus.com/forum/beginner/3958/ – Corey Ogburn May 28 '12 at 08:50
  • @EitanT - It depends on the definition of *at all*. :-) For example - with pointers, operator chaining would look like `*(*pX + *pY) + *pZ` instead of `X + Y + Z`. One of them surely looks better! – Bo Persson May 28 '12 at 08:54
  • I read somewhere that Bjarne Stroustrup thought the C-style pointer syntax was ugly and prefered the object-style syntax. – Brady May 28 '12 at 08:59
  • 1
    Why do you need classes or functions, when you could do all coding inside a single main-file? Maybe an attempt to a rule of thumb: Programming languages are not there to make programming possible, but to make programming easy (or hard, of course). – Sebastian Mach Oct 30 '14 at 10:48
  • 1
    @phresnel There's a difference between functionality and redundancy in programming languages. The reason for the existence of function and classes is clear to me. I was not sure about references, hence the question. – Eitan T Nov 02 '14 at 08:00

5 Answers5

11
  • 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.
Luchian Grigore
  • 253,575
  • 64
  • 457
  • 625
8

Operator overloading. Using pointers for "passing via reference" would give you unacceptable syntax.

zch
  • 14,931
  • 2
  • 41
  • 49
  • 3
    @EitanT It is the reason C++ introduced references in the first place. – James Kanze May 28 '12 at 08:47
  • Maybe, without reference, the compiler itself will pass a pointer to const instead of a reference. Not considering type safety I think references are just "sugar". – Adriano Repetti May 28 '12 at 08:49
  • @Adriano - but then you couldn't pass or return by value. – zch May 28 '12 at 08:52
  • But a reference is passed by...reference. They make syntax more clear but the generated code isn't so different from regular pointers. As pointed by Stroustrup in the link posted by @EitanT the problem is operator overloading with pointers is **ugly**. Not impossible, just ugly. – Adriano Repetti May 28 '12 at 09:05
  • @Adriano Actually, impossible, since you can't take the address of an rvalue. If pointers had been used for overloading, `&x + &y` would be possible, but how would you write `x + y + z`? – James Kanze May 28 '12 at 09:44
  • @JamesKanze of course without references there must be some compiler support for that. As it does with references. – Adriano Repetti May 28 '12 at 09:59
  • While we can deduce from more energetic respondents that this was the primary reason, without a citation, this is barely a comment, and certainly not an answer. But hey, there's no accounting for taste! – underscore_d Feb 26 '16 at 02:40
  • So why doesn't the compiler simply let you write: Foo operator +(const Foo* x, const Foo* y) and use it via "Foo a, b; a + b" (i.e. implicitly prepend "&"). You could jettison a whole bunch of rules and syntax from the language and still be just as powerful. And the amount of implicitness in the language would be much less overall. – matvore May 01 '18 at 19:42
4

If you have a pointer as a parameter, you have to check if it is NULL. With references, you do have to make that check. Here is why there is references in C++ from the man himself - http://www.stroustrup.com/bs_faq2.html#pointers-and-references

Superman
  • 3,027
  • 1
  • 15
  • 10
  • 1
    That link is now broken. – ntc2 May 23 '14 at 22:29
  • Thanks @ntc2 for pointing it out. Fixed the link. – Superman May 28 '14 at 08:29
  • The citation gives the main reason references were added to C++, so props for being the only person who bothered to try citing... but it's weird that you didn't even attempt to summarise that, opting to talk about something else instead. And the answer that _does_ mention the real reason doesn't cite it... _wassupwiddat_. – underscore_d Feb 26 '16 at 02:43
0

Example:

my_type *get_some_data();
...
my_type *data = get_some_data();

allowes to do delete data while

my_type &get_some_data();
...
my_type &data = get_some_data();

gives no way for deletion.

tonytony
  • 1,994
  • 3
  • 20
  • 27
  • 2
    It's unconventional, but couldn't you just do `delete &data` in the latter? – Eitan T May 28 '12 at 08:51
  • @EitanT I haven't thought of it :D I believed that I can prohibit deletion by returning reference instead of pointer =) – tonytony May 28 '12 at 08:56
  • 1
    You can call delete on either, and it isn't guaranteed to be safe in either case. There is no way the caller can know that they can delete the object being pointed to or referred to. – juanchopanza May 28 '12 at 09:14
  • It's a little bit compiler dependent but I _guess_ the rule could be at least checked by the debug version of new/delete (then it'll throw an exception where you'll try to delete that object). – Adriano Repetti May 28 '12 at 09:17
0
class A{
public:
    A(int i){}
};

void foo(const A& a){};
void foo2(const A* pa){};
int main (void)
{
  foo(1);
  foo2(1); //invalid
  return (0);
}

One case I know.The user don't need to manage the reference object, the compiler can destroy it. Since the pointer requires the user to delete the it explicit. For foo2, it hard to manage the temporary life cycle.

RolandXu
  • 3,566
  • 2
  • 17
  • 23