vendredi 25 janvier 2019

Why does C++11 contain an odd clause about comparing void pointers?

While checking the references for another question, I noticed an odd clause in C++11, at [expr.rel] ¶3:

Pointers to void (after pointer conversions) can be compared, with a result defined as follows: If both pointers represent the same address or are both the null pointer value, the result is true if the operator is <= or >= and false otherwise; otherwise the result is unspecified.

This seems to mean that, once two pointers have been casted to void *, their ordering relation is no longer guaranteed; for example, this:

int foo[] = {1, 2, 3, 4, 5};
void *a = &foo[0];
void *b = &foo[1];
std::cout<<(a < b);

would seem to be unspecified.

Interestingly, this clause wasn't there in C++03 and disappeared in C++14, which seems to mean that the previous clauses apply. If we take the example above and apply the C++14 wording to it, I'd say that ¶3.1

  • If two pointers point to different elements of the same array, or to subobjects thereof, the pointer to the element with the higher subscript compares greater.

as a and b point to elements of the same array, even though they have been casted to void *.

Am I right in my understanding? What was the point of that oddball clause added in C++11 and immediately removed?

Aucun commentaire:

Enregistrer un commentaire