c++object-model

Why is there a rule that temporary objects must have distinct addresses?


The situation of my interest is

const int &n1 = 123;
const int &n2 = 123;

I know it is something as if the literal 123 is the parameter for initializing a temporary int and const is just a boring compile time check, but I want to know the reason why distinct temporaries are needed in this case, instead of n1 and n2 both having the same temporary.

I know the rule exists but do not know why this rule exists.


Solution

  • If you want them to have the same address, you can always do const int &n2 = n1. If you do it in another way, the compiler may suspect you have your own reason to do that.

    The compiler is not allowed to guess what your concern is. It implements what you write. Doing an optimisation as your suggest would imply that the comparison bool test = &n1 == &n2 will give another result. Generally speaking, the compiler is allowed to make optimisation, as long as the result is not modified.

    You should consider that previous compilers were much less efficient than now. Such an optimisation or a language feature should have been impossible 30 years ago. So, it if it is not an optimisation, it will be a modification of the language that would potentially change the behaviour of many existing programs.