0
MyObject obj = new MyObject(k);
foo(obj);
bar(&obj);

foo(MyObject &)
bar(MyObject *)

I know we need to use the passed parameter differently in the two functions, but apart from that, in terms of memory allocation or otherwise, is there a difference between the two? I mean for the reference also the compiler would be storing the memory pointer.

Michael Petrotta
  • 59,888
  • 27
  • 145
  • 179
  • The code doesn't compile. – Kerrek SB Sep 29 '13 at 18:30
  • I'd be surprised if there was a difference. I guess in some circumstances the compiler might be able to optimise the reference version better, but that would be it I think. – john Sep 29 '13 at 19:12

2 Answers2

1

From the point of view of the compiler (i.e. the generated machine code) there is no substantial difference.

I'm not sure but I wouldn't be surprised to discover that cfront used direct translation of reference arguments to pointers.

At the language level there are however many differences; for example a reference is formally always bound to an object (i.e. you don't have a "NULL reference") and also a reference cannot be rebound (while a pointer variable can be made to point to something else).

6502
  • 112,025
  • 15
  • 165
  • 265
0

One important difference is that a pointer can be nullptr, where as C++ has no concept of a null reference.

Adam Burry
  • 1,904
  • 13
  • 20