Re: What does the initialization of a reference object do?
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?
Sorry, bad wording or perhaps thinking: it shouldn't compile /cleanly/.
The C++ standard can't prevent it from happening, because a reference
that's not to a valid object can be produced by code that's impossible
to analyse -- e.g., whether the reference is valid or not could depend
on the solution to some intractable mathematical problem.
The wording "shall" above means that if the code does produce a
rerefence that's not to a valid object, it has Undefined Behavior.
A quality compiler will detect the most flagrant violations, such as the
above, and issue a diagnostic (warning or error), just as with e.g.
calling a pure virtual function from a constructor -- which is the
same kind of impossible-to-analyze problem for the general case. Comeau
Online 4.3.3 with default settings warns about your code. Visual C++
7.1 with /W4 warns. MingW g++ 3.4.4 with -Wall and -pedantic warns.
With some compilers you have to instruct them to issue warnings. Since
I have that by default I don't know whether the compilers mentioned will
issue warnings if you don't up the default warning level. But that's
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.
Not OK: undefined behavior means undefined behavior, including what one
might "expect" were it not for the undefined behavior.
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
Q: What is the most annoying thing on usenet and in e-mail?