问题
Thinking of this question Why can I initialize reference member with data member before initializing the data member? as well as this Why is initialization of a new variable by itself valid? following strange code came to my mind:
int main()
{
int &ri = ri;
ri = 0;
}
This code compiles live demo, I know this is UB, but just wonder, what happens inside compiler, where this reference actually points to?
Update: different situation happens when that reference is global: godbolt, gcc seems to declare it as a pointer and make it to point to itself
Note for downvoters: I know this code is invalid and I am not expecting particular behavior from a compiler, but I think looking inside may help to understand why following code is not illegal and how references work in the language:
struct foo {
int &ri = i;
int i = 0;
};
or this:
extern int i;
int &ri = i;
int i = 0;
Update2: while assignment is definitely UB, it is a good question, if declaration itself:
int &ri = ri;
is UB or not. This seem to be is pure evil - ri
cannot be used in any way, but declaration itself seems to be vaild.
回答1:
Not an answer, just a long comment.
I do not know what you mean by "...it would not compile on C++ without cast...".
How references must be implemented, it is not specified as far as I know. However, they must be pointers in disguise (what else could they be?). The references source and the pointers source will generate exactly the same code.
"...does not have to be represented in memory at all,..." I am not sure I understand what this means. The address of a reference is the address of the object it refers to. Therefore you might say the reference itself has no address. The following will print i
's address twice:
int i;
int &ri = i;
cout << &ri << endl << &i;
Since the language allows the use of uninitialized variables, I think a good compiler must issue an warning but not an error: uninitialized variable used
.
[EDIT]
I had a short discussion with someone involved in the design of C++ (I forgot to ask permission to name him). In short, banning T x = x;
is desirable, but C++ was not designed from scratch: it had to be backward compatible with C.
So, you found a legal way to create an uninitialized reference. The answer to "...where this reference actually points to?" is: where an uninitialized pointer points.
来源:https://stackoverflow.com/questions/51426859/c-reference-to-nowhere