Comparing pointers to unrelated objects has unspecified results.
That would seem to suggest that this program may have undefined behaviour, at the very least because we cannot guarantee a strict weak ordering on the key type:
#include <map>
int main()
{
int x = 0, y = 1;
bool arbitrary = false;
std::map<int*, bool> m{
{&x, arbitrary},
{&y, arbitrary}
};
}
More generally, then, can we say that a map with pointer keys is a dangerous* proposition? Or is there some special rule we can lean on here?
* Academically speaking, that is; in reality I'm not aware of mainstream implementations that will actually raise hell over comparing arbitrary pointers.
Yes, because std::map
default comparison operator is std::less
, which, unlike the standard comparison operator, is completely defined for pointer types.
For templates less, greater, less_equal, and greater_equal, the specializations for any pointer type yield a result consistent with the implementation-defined strict total order over pointers ([defns.order.ptr]).
The implementation-defined strict total order over pointers is defined in [defns.order.ptr] as:
implementation-defined strict total ordering over all pointer values such that the ordering is consistent with the partial order imposed by the builtin operators <, >, <=, >=, and <=>