Question

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?

No correct solution

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top