Why do some c++ compilers let you take the address of a literal?

半城伤御伤魂 提交于 2020-01-10 20:01:14

问题


A C++ compiler that I will not name lets you take the address of a literal, int *p = &42;

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?


回答1:


What if you needed a pointer to an integer with the value of 42? :)

C++ references are much like automatically dereferenced pointers. One can create a constant reference to a literal, like this:

const int &x = 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.




回答2:


Because 42 is the answer to life, the universe and everything. When asked for its address it is the answer itself.




回答3:


Tongue slightly (nut by no means totally) in cheek:

I'd say that in C++ application code taking the address of an integer whether lvalue or rvalue is almost always a mistake. Even using integers, for doing anything much more than controlling loops or counting is probably a design error, and if you need to pass an integer to a function which might change it, use a reference.




回答4:


Found something related to rvalue references in C++0x -- move semantics http://www.artima.com/cppsource/rvalue.html




回答5:


It effectively requires the compiler to initialize a pointer with the address of an integer with the value 42

Then why, in some compilers, we can't take the address of a literal directly ?

int* ptr = &10;

The reference:

int& ref = 10;

is almost the same thing as a pointer, though...



来源:https://stackoverflow.com/questions/1166378/why-do-some-c-compilers-let-you-take-the-address-of-a-literal

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