4

In some C++ sources I saw that an expression result can be saved as a constant reverence. Like this:

 const int &x = y + 1;

What does it mean? Is there any documentation on this? I can't find it..


For me it seems to be equivalent to:

 const int x = y + 1;

since result of the program stays the same. Is it truly equivalent?

If yes why does the language allows the first way to write it at all? It looks confusing.

If no what is the difference?

klm123
  • 12,105
  • 14
  • 57
  • 95
  • The first one is tricky. AFAIK what it does is creating a constant reference to the temporary that is obtained by computing `y + 1`. –  Oct 29 '13 at 18:28
  • 1
    @H2CO3 Not quite, AFAIK, the expression `y+1` produces a value but not a temporary (object). Therefore, the reference binding itself creates the temporary. – dyp Oct 29 '13 at 18:30

1 Answers1

5

The difference should be whether or not the result is copied/moved. In the first case:

const int& x = y + 1;

The value of y+1 is essentially saved as a temporary value. We then initialize a reference x to this temporary result. In the other case:

const int x = y + 1;

We compute y + 1 and initialize a constant variable x with the value.

In practice with integers there will be no visible difference. If y+1 happened to be a large data structure, e.g., a class which is 1MB of data, this could make a significant difference.

pippin1289
  • 4,861
  • 2
  • 22
  • 37
  • 2
    Also, it's essentially impossible to notice any difference in behaviour after this line. After initialization, `x` behaves exactly the same either way. With a larger data structure, it may call the copy constructor within `const X x = y + 1`. (Or it might *elide* it). On the other hand, `const X &x = y + 1` is guaranteed not to call the copy constructor. – Aaron McDaid Oct 29 '13 at 18:32
  • This doesn't address why the language allows you to do this, which I believe is related to allowing you to call functions taking const references with temporaries. – David Brown Oct 29 '13 at 18:43
  • Thanks! If x refers to temporary result is it safe to use it? – klm123 Oct 29 '13 at 19:31