Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

rvalue

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?

like image 245
S I Avatar asked Feb 28 '23 12:02

S I


1 Answers

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.

like image 169
Barry Kelly Avatar answered Apr 28 '23 03:04

Barry Kelly