为什么有一个规则,即临时对象必须具有不同的地址? [英] Why is there a rule that temporary objects must have distinct addresses?

查看:62
本文介绍了为什么有一个规则,即临时对象必须具有不同的地址?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我感兴趣的情况是

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

我知道好像字面值123是用于初始化临时int的参数,而const只是无聊的编译时检查,但是我想知道为什么在其中需要不同的临时变量的原因在这种情况下,不是n1n2都具有相同的临时值.

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.

推荐答案

如果希望它们具有相同的地址,则始终可以执行const int &n2 = n1.如果您以其他方式执行此操作,则编译器可能会怀疑您有自己的理由.

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.

不允许编译器猜测您关心的是什么.它实现您编写的内容.根据您的建议进行优化将暗示比较bool test = &n1 == &n2将给出另一个结果.一般来说,只要不修改结果,就可以允许编译器进行优化.

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.

您应该考虑到以前的编译器的效率要比现在低得多.这种优化或语言功能在30年前是不可能的.因此,如果不是最优化的话,那将是对语言的修改,有可能改变许多现有程序的行为.

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.

这篇关于为什么有一个规则,即临时对象必须具有不同的地址?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆