Just for fun, I had a std::list
开发者_JAVA百科of const char*
, each element pointing to a null-terminated text string, and ran a std::list::sort()
on it. As it happens, it sort of (no pun intended) did not sort the strings. Considering that it was working on pointers, that makes sense.
According to the documentation of std::list::sort()
, it (by default) uses the operator <
between the elements to compare.
Forgetting about the list for a moment, my actual question is: How do these (>, <, >=, <=) operators work on pointers in C++ and C? Do they simply compare the actual memory addresses?
char* p1 = (char*) 0xDAB0BC47;
char* p2 = (char*) 0xBABEC475;
e.g. on a 32-bit, little-endian system, p1
> p2
because 0xDAB0BC47
> 0xBABEC475
?
Testing seems to confirm this, but I thought it'd be good to put it on StackOverflow for future reference. C and C++ both do some weird things to pointers, so you never really know...
In C++, you can't compare just any pointers using the relational operators. You can only compare two pointers that point to elements in the same array or two pointers that point to members of the same object. (You can also compare a pointer with itself, of course.)
You can, however, use std::less
and the other relational comparison function objects to compare any two pointers. The results are implementation-defined, but it is guaranteed that there is a total ordering.
If you have a flat address space, it's likely that pointer comparisons just compare addresses as if they are integers.
(I believe the rules are the same in C, without the comparison function objects, but someone will have to confirm that; I'm not nearly as familiar with C as I am with C++.)
This is just a supplementation.
In C++ 20.3.3/8:
For templates greater, less, greater_equal, and less_equal, the specializations for any pointer type yield a total order, even if the built-in operators <, >, <=, >= do not.
In C 6.5.8/5:
If two pointers to object or incomplete types both point to the same object, or both point one past the last element of the same array object, they compare equal. If the objects pointed to are members of the same aggregate object, pointers to structure members declared later compare greater than pointers to members declared earlier in the structure, and pointers to array elements with larger subscript values compare greater than pointers to elements of the same array with lower subscript values. All pointers to members of the same union object compare equal. If the expression P points to an element of an array object and the expression Q points to the last element of the same array object, the pointer expression Q+1 compares greater than P. In all other cases, the behavior is undefined.
So, I think comparing char const*
which belong to two different '\0'-terminated-string as in the question is an undefined behavior (in C).
Yes, they just compare memory address.
精彩评论