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

216 views Asked by At

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.

2

There are 2 answers

14
Damien On BEST ANSWER

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.

3
YSC On
const int &n1 = 123;
const int &n2 = 123;

I want to know the reason why distinct temporaries are needed in this case.

Because the C++ committee probably didn't care for this specific case. What was on their mind, what was their aim, was to provide rules on how temporary are handled in the more useful and common case: evaluation of full-expression chaining creation, use and destruction of temporaries:

class A { /* ... */ };
A make_a();
void consume_a(A&&);
void use_a(A const&);

consume_a(make_a());
use_a(make_a());

It's obvious make_a() needs to produce a different temporary A each time.