Re: STL map question : directed to stl map expert(s)....
* Craig Scott:
Firstly though, I'd appreciate it if someone could point me at the
part of the standard which talks about comparing pointers for inequality
being valid only if they both point into the same array.
No, it's about magnitude comparision, and the main rule is, in ?5.9/2
"If two pointers p and q of the same type point to different objects
that are not members of the same object or elements of the same array
or to different functions, or if only one of them is null, the results
of p<q, p>q, p<=q, and p>=q are unspecified".
plus,
"If two pointers point to nostatic data members of the same object
separated by an access-specifier label the result is unspecified."
Suprisingly this is at a logical place in the standard, ?5.9 is about
"Relational operators".
"Unspecified" means that any particular compiler should /document/ the
behavior for that compiler, i.e. that every conforming compiler will
provide some reasonable, documented behavior, but that different
compilers can provide different behaviors.
The above-quoted comments get interesting if you have a std::map where the
key_type is a pointer. The default comparison for such a map is
less<key_type>, which for a pointer has default implementation a < b. Now
I'm wondering under what circumstances such comparisons are technically
legal. I'd be interested in which of the following cases are valid and
which are not:
int a[2] = { 6, 7 }
int b = 1;
int c = 2;
std::map<int*,int> myMap1;
myMap1[&a[0]] = 15; // (1)
myMap1[&a[1]] = 16; // (2)
myMap1[&b] = 17; // (3)
std::map<int*,int> myMap2;
myMap[&b] = 25; // (4)
myMap[&c] = 26; // (5)
Will any of (1)-(5) lead to undefined behavior?
No. std::less etc. provide stronger guarantees than the built-in
relational operators. You can compare pointers freely (except invalid
pointers) using the standard library's comparision functors, but
possibly at the cost of some inefficiency.
Cheers, & hth.,
- Alf
--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]