本文介绍了是运算符< (小于)在指针上是否一致?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

注意:此问题与总订单无关.可以使用std::less获得相同类型的指针的总顺序.

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.

从哪种意义上说,这是不允许的?是实施定义的,未指定的还是未定义的行为?

我想我在某处读到了未指定的内容.不需要实现来记录行为是什么,但是必须有一些行为.因此,这意味着比较任何两个指针仍然是合法的,但不必产生总顺序. 这是否意味着,当两次比较相同的两个指针时,我们仍然必须获得一致的结果?一般情况是:在应用程序中两次调用相同的未指定行为是否总是产生相同的结果? ?

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?

推荐答案

比较两个不相关的指针(即,指针不指向同一内存,或者不指向同一数组"的不同部分)只能使用相等性来完成==和不等式!=.所有其他比较都是未指定.

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.

所以,如果您有

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

您只能 使用==!=比较指针p1p2.

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

但是如果你有

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

然后您还可以使用<>(当然还有<=>=)来比较p1p2

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

这篇关于是运算符&lt; (小于)在指针上是否一致?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-29 13:48