Topic: Defect Report: references to uninitialized objects


Author: Gennaro Prota <gennaro_prota@yahoo.com>
Date: Tue, 20 Jan 2004 19:56:29 +0000 (UTC)
Raw View
[Note: Forwarded to C++ Commitee -sdc ]

8.3.2 [dcl.ref] paragraph 4 says:

  A reference shall be initialized to refer to a valid object or
  function. [Note: in particular, a null reference cannot exist
  in a well-defined program, because the only way to create such
  a reference would be to bind it to the "object" obtained by
  dereferencing a null pointer, which causes undefined behavior
  ...]

What is a "valid" object? In particular the expression "valid object"
seems to exclude uninitialized objects, but the response to Core Issue
363 clearly says that's not the intent. This is an example
(overloading construction on constness of *this) by John Potter, which
I think is supposed to be legal C++ though it binds references to
objects that are not initialized yet:

 struct Fun {
    int x, y;
    Fun (int x, Fun const&) : x(x), y(42) { }
    Fun (int x, Fun&) : x(x), y(0) { }
  };
  int main () {
    const Fun f1 (13, f1);
    Fun f2 (13, f2);
    cout << f1.y << " " << f2.y << "\n";
  }


Proposed resolution: Changing the final part of 8.3.2 [dcl.ref],
paragraph 4 to:

  A reference shall be initialized to refer to an object or function.
  From its point of declaration on (see 3.3.1) its name is an lvalue
  which refers to that object or function. The reference may be
  initialized to refer to an uninitialized object but, in that case,
  it is usable in limited ways (3.8, paragraph 6) [Note: OTOH, a
  declaration like this:

    int & ref = *(int*)0;

  is ill-formed because ref will not refer to any object or function
  ]


I also think a "No diagnostic is required." would better be added
(what about something like int& r = r; ?)


Genny.



[ comp.std.c++ is moderated.  To submit articles, try just posting with ]
[ your news-reader.  If that fails, use mailto:std-c++@ncar.ucar.edu    ]
[              --- Please see the FAQ before posting. ---               ]
[ FAQ: http://www.jamesd.demon.co.uk/csc/faq.html                       ]