Re: What does the initialization of a reference object do?
"ziman137" <gangxu_csu@yahoo.com> wrote in message
news:1148720721.201262.17630@38g2000cwa.googlegroups.com
Alf P. Steinbach wrote:
A& a = a;
Should not compile; ?8.5.3/1 "A variable declared to be a T&, that is
"reference to type T" (8.3.2), shall be initialized by an object",
also ?8.3.2/4 "A reference shall be initialized to refer to a valid
object or function", and 'a' is not a valid object.
Thanks for your answer. I did understand this.
It should not compile? If a reference object is assumed to be just
initialized in the manner of an internal pointer, which points to the
target "object" address, or is assigned by target "this" pointer, it
may well compile. No doubt it is a bad statement - my question is, how
exactly does C++ standard prevent this "should-not" from happening?
By the way, this was exactly where I got confused. My problem was, it
did compile using GNU C++ on Linux (Redhat, see below). Not only being
compiled, it also invokes "a.foo()" OK. Could you, or someone else,
please help me understand whether this is a compiler implementation
issue, or this has something to do with the reference initialization
in ISO C++ standard?
It doesn't have anything specifically to do with references.
A a = a;
will also compile on VC++ 8 and Comeau online. It is a nonsense, just like
your code. It involves undefined behaviour, but lots of things that involve
undefined behaviour still compile. Some of them also run correctly. That is
what undefined means --- the outcome could be anything. Empirical
observation suggests that nonsense initializations will "work" if your class
does not in fact have anything that needs initializing (or if you make no
use of the stuff that does).
Likewise your
a.foo();
is undefined behaviour that you can sometimes get away with.
Try this:
A * ptr;
ptr->foo();
That probably works too.
PS. Corrected Code to Conform to Group Posting Standard
// foo.cpp
#include <iostream>
using namespace std;
struct A {
A () { cout << "A() ctor!" << endl; };
~A() { cout << "~A() dtor!" << endl; };
void foo () { cout << "this=" << this << endl; };
};
int main ()
{
A& a = a; // it does compile with GNU C++ compiler
cout << "&a=" << &a << endl;
a.foo(); // is it legal here?
A a1;
A& a2 = a1;
cout << "&a1=" << &a1 << endl;
cout << "a2."; a2.foo();
return 0;
}
gcc version 3.2.2 20030222 (Red Hat Linux 3.2.2-5)
g++ -o foo foo.cpp
foo
&a=0x80488ba
this=0x80488ba
A() ctor!
&a1=0xbfffd8e0
a2.this=0xbfffd8e0
~A() dtor!
Running this is debug mode under VC++ 8 gives:
&a=CCCCCCCC
this=CCCCCCCC
A() ctor!
&a1=0012FF37
a2.this=0012FF37
~A() dtor!
The CCCCCCCC address values indicate uninitialized data (in debug mode only,
the compiler initializes the variables to CCCCCCCC, so that if they stay
that way, then you know the program has failed to initialize them).
--
John Carson