Topic: STL set flaw (correction)


Author: Nathan Myers <ncm@cantrip.org>
Date: 1996/06/06
Raw View
Nathan Myers wrote:

> The language does not currently provide *any* mechanism to generate a
> total ordering of pointers.  ...  there is no fully portable
> alternative but to give each object a numeric ID and sort them on that
> basis, or to hash the pointers and compare them for true equality during
> lookup.

A correction, in light of other answers...

Hashing pointer values, and then comparing for equality, is itself not
strictly portable, because two pointers to the same storage might hash
to different buckets.  This is rarely (but still possibly) a problem on
real architectures if the pointers are simply copied, but is quite likely
if arithmetic is used on them.

For example:

  p = q + 3;
  --p; --p; --p;
  assert(hash(p) == hash(q)); // might fail!

This sort of problem is pretty common on PC compilers, and I have
even seen (on a Borland compiler from a couple of years ago) the
following loop fail to terminate:

  int a[100];
  int* p = a + 100;
  while (p != a) { --p; ... }

(Note that the behavior of the apparently similar

  while (p-- != a) { ... }

is undefined, because p gets a value outside the range [a,a+100].)

Nathan Myers
ncm@cantrip.org  http://www.cantrip.org/
---
[ 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         ]
[ FAQ:      http://reality.sgi.com/employees/austern_mti/std-c++/faq.html    ]
[ Policy:   http://reality.sgi.com/employees/austern_mti/std-c++/policy.html ]
[ Comments? mailto:std-c++-request@ncar.ucar.edu                             ]