0

I would like to know how references are really implemented in C++. I mean, initialization of a réference? Is it more efficient to handle a reference or a pointer?

for example:

int i = 7;
int &j = i;   // how is this ligne compiled?
int *k = &i;  // is it less efficient doing this?

And is the case of objets, is there any diffrence in managing reference?

ThunderPhoenix
  • 1,649
  • 4
  • 20
  • 47
  • 2
    The C++ standard doesn't say how references are implemented. – msc Apr 13 '17 at 11:15
  • 1
    Most compilers will just make a note that `i` and `j` mean the same thing and not generate any code for that. – Bo Persson Apr 13 '17 at 11:25
  • OP is thinking of C++ as a one-to-one translation of machine code, rather than as a description of a program semantics. OP should stop doing that. – Lightness Races in Orbit Apr 13 '17 at 11:33
  • @BoundaryImposition, I understand. But I wanted to know if it is more efficient to use references or pointers. – ThunderPhoenix Apr 13 '17 at 11:38
  • Most compilers implement reference as `constant-pointers` i.e. `int & j = i;` would be treated as `int * const ptr = &i;`. Now, `ptr` can't be modified which we want here because references can't be reassigned. But this is universal behavior of all compilers !! – Pravar Jawalekar Apr 13 '17 at 11:43
  • You should not use a reference over a pointer to gain performance, even if it would be faster (which i doubt). You should choose what you use by the semantics of your target. If you do not own the target, and do not need to change the pointer, take a reference. – OutOfBound Apr 13 '17 at 11:48
  • @watou: Your question shows that you don't. – Lightness Races in Orbit Apr 13 '17 at 11:58

0 Answers0