Is operator< (less than) on pointers consistent

2020-06-18 03:03发布

Note: This question is not about total order. A total order on pointers of the same type can be obtained using std::less.

According to this, comparing two pointers with operator< isn't allowed if they point for example into different allocations.

In which sense isn't it allowed? Is it implementation defined, unspecified or undefined behaviour?

I think I read somewhere that it's unspecified. An implementation isn't required to document what the behaviour is, but there must be some behaviour. So that would mean, comparing any two pointers is still legal, but doesn't neccessarily yield a total order. Does that mean, that we still have to get a consistent result, when comparing the same two pointers twice? The general case would be: Does invoking the same unspecified behaviour twice within an application always yield the same result?

int i1, i2;
int* a = &i1;
int* b = &i2;
bool b1 = a < b; // unspecified, right?
bool b2 = a < b;
assert(b1 == b2); // Is this guaranteed to be true?

标签: c++ pointers
2条回答
甜甜的少女心
2楼-- · 2020-06-18 03:20

Comparing pointers as shown in your example makes little sense because "a" and "b" value depends on how is the data stored in memory, not on the content stored in that location.

Pointers are addresses in memory (usually stored as 32 bit integer). Unless you change any of them, their comparison will return the same result. You might not know what that result is, but you'll know that it'll be the same every time.

Therefore, in your case, you will get the same result for both b1 and b2, so the assertion will pass.

Here is an example where comparing pointers does make sense:

int data[1000];
int *end = data + 50;
for (int *c = data; c < end; c++)
     ... use *c
查看更多
何必那么认真
3楼-- · 2020-06-18 03:37

Comparing two unrelated pointers (i.e. pointers not pointing to the same memory, or not pointing to different parts of the same "array") can only be done using equality == and inequality !=. All other comparison is unspecified.

If you have two pointers pointing to the same place, or inside the same array, then you can compare them using the relative operators.

So if you have e.g.

int* p1 = new int[10];
int* p2 = new int[5];

you can only use == and != to compare the pointers p1 and p2.

But if you have

int a = new int[10];
int* p1 = &a[0];
int* p2 = &a[3];

then you can use also < and > (and of course <= and >=) to compare p1 and p2

查看更多
登录 后发表回答