Re: OONSTD: Amateur Programmers

Kent Budge (kgbudge@valinor.sandia.gov)
Fri, 26 Mar 1999 12:05:37 -0700 (MST)

>> The question of the day : why is it too difficult to use reference types
>> in STL template arguments ? [map<Vector const &, Vector const &> won't
>> compile : reference to reference type]
>
>An object can be put in a standard container iff it meets the
>"CopyConstructible" and "Assignable" requirements. References don't.
>
>-- Gaby

To illuminate further, the problem is that a reference is not an
object. It's an alias for an object. Container classes can usually
only contain actual objects.

If your container is a vector, then somewhere deep in the definition of
the vector class template you will encounter one or more expressions of
the form "new T[size]". In this expression, T must be an object type;
it can't be a reference type. There are several reasons why. (1) The
expression "new T[size]" returns a pointer to T, but pointers to
references are explicitly forbidden by the language definition. (2)
The expression "new T[size]" behaves like the definition of an array,
but arrays of references are explicitly forbidden by the language
definition. (3) A reference must be declared with a non-empty
initializer, but the expression "new T[size]" behaves like the
definition of an array with no initializers.

If your container is a list, then somewhere deep in the list class
template you will see a helper class, typically a private struct, that
contains an instance of T and a pointer to its own type. These are the
links in the list. Such a list could work for T a reference type (and
might even be useful, now that I think about it) but it must be coded
carefully, because each link must have its reference to T initialized
properly. Remember, a reference must *always* be initialized the
instant it is defined, and thereafter the reference is immutable.
(Though not the object it refers to.) I don't know off-hand if STL's
list class attempts such careful coding.

You can, of course, define a template class that has semantics of
reference to T. It would basically wrap a pointer. Its copy
constructor would set the value of the pointer, while its assignment
would set the value of the object pointed to. Unfortunately, such a
class would probably behave badly within STL, because STL tends to
assume assignment and copy have identical semantics, which is certainly
not the case for a reference class.

Kent G. Budge
Sandia National Laboratories