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

落花浮王杯 提交于 2019-12-23 12:09:45

问题


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.


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/53426022/why-is-there-a-rule-that-temporary-objects-must-have-distinct-addresses

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!