Re: Reference to myself compiles... and crashes.
Am 06.09.2011 00:20, schrieb Javier Jimenez:
The example code bellow compiles in gcc, and produces a core dump.
When I noticed the error ( int& i = i; ), I would expected two
possible compiler behaviours:
- it does not compile.
There is currently a still open core issue related to this kind of
errors, see
http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#504
- the reference points to the "i" out of the "if context" (const int
i)
No, this does not happen. A variable declaration introduces a name that
is immediately available in the initializer. There exist reasonable
examples where this can be useful, e.g.
void* p = &p;
can be considered as some "magic" address.
But my surprise is that it does compile... and crashes in runtime.
Why?
The current language requires this, as explained above.
// main.cpp
int fillstack()
{
int dummy = 42;
return dummy;
}
int main()
{
const int i = fillstack();
if ( true )
{
int& i = i;
return i;
}
}
g++ -Wall ?o main main.cpp
g++ -Wall ?O3 ?o main main.cpp
g++ -Wall ?g ?o main main.cpp
If a compiler does not diagnose this, you should prepare an enhancement
request for this.
HTH & Greetings from Bremen,
Daniel Kr?gler
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]