问题描述
一个C ++编译器,我不会命名,让你取一个文字的地址,int * p =&42;
A C++ compiler that I will not name lets you take the address of a literal, int *p = &42;
清楚地,42是r值,大多数编译器拒绝这样做。
Clearly 42 is an r-value and most compilers refuse to do so.
为什么编译器允许这个?
Why would a compiler allow this? What could you do with this other than shoot yourself in the foot?
推荐答案
如果你需要一个指向整数的指针,值42? :)
What if you needed a pointer to an integer with the value of 42? :)
C ++引用与自动引用的指针非常相似。可以创建一个对文字的常量引用,如下:
C++ references are much like automatically dereferenced pointers. One can create a constant reference to a literal, like this:
const int &x = 42;
它有效地要求编译器使用值为42的整数的地址初始化指针,因为你可以随后这样做:
It effectively requires the compiler to initialize a pointer with the address of an integer with the value 42, as you might subsequently do this:
const int *y = &x;
结合这一点,编译器需要有逻辑来区分没有地址采取,一个有,所以它知道将其存储在内存中。第一个不需要具有存储器位置,因为它可以是完全临时的并且存储在寄存器中,或者可以通过优化来消除。取值的地址可能会引入别名,编译器无法跟踪和禁止优化。因此,应用 &
运算符可能会将值(无论是什么)强制到内存中。
Combine that with the fact that compilers need to have logic to distinguish between a value which has not had its address taken, and one which has, so it knows to store it in memory. The first need not have a memory location, as it can be entirely temporary and stored in a register, or it may be eliminated by optimization. Taking the address of the value potentially introduces an alias the compiler can't track and inhibits optimization. So, applying the &
operator may force the value, whatever it is, into memory.
所以,你可能发现一个错误,结合这两个效果。
So, it's possible you found a bug that combined these two effects.
这篇关于为什么有些c ++编译器让你拿一个字面量的地址?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!