std :: less必须与指针类型的相等运算符一致吗? [英] Does std::less have to be consistent with the equality operator for pointer types?

查看:338
本文介绍了std :: less必须与指针类型的相等运算符一致吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

昨天我碰到了一个问题,我最终转化为以下最小示例。

  #include< iostream> 
#include< functional>

int main()
{
int i = 0,j = 0;
std :: cout
<< (& i ==& j)
<< std :: less< int *>()(& i,& j)
< std :: less< int *>()(& j,& i)
< std :: endl;
}

此特定程序在使用启用优化的MSVC 9.0编译时,输出 000 。这意味着


  1. 指针不相等,

  2. 另一个根据 std :: less ,这意味着两个指针根据 std :: less

此行为是否正确?是 std :: less 的总顺序是否不需要与等于运算符?



是以下程序允许输出 1

  #include< iostream& 
#include< set>

int main()
{
int i = 0,j = 0;
std :: set< int *> s;
s.insert(& i);
s.insert(& j);
std :: cout<< s.size()<< std :: endl;
}


解决方案

违反! Panic!



以下20.3.3 / 8(C ++ 03):


对于模板更大,更小,
greater_equal和less_equal,
任何指针类型的特殊化
产生一个总顺序,即使
内置运算符< >,<=,> = do
not。


似乎一种情况是急切的优化导致不正确的代码。 ..



编辑:C ++ 0x也会将这个值保留在20.8.5 / 8之下



编辑2:很奇怪,作为第二个问题的答案:



以下5.10 / 1 C ++ 03: / p>


两个相同类型的指针比较
等于且仅当它们都是
null时,都指向相同的函数,
或两者表示相同的地址


这里有很多错误。 >

I've bumped into a problem yesterday, which I eventually distilled into the following minimal example.

#include <iostream>
#include <functional>

int main()
{
    int i=0, j=0;
    std::cout
        << (&i == &j)
        << std::less<int *>()(&i, &j)
        << std::less<int *>()(&j, &i)
        << std::endl;
}

This particular program, when compiled using MSVC 9.0 with optimizations enabled, outputs 000. This implies that

  1. the pointers are not equal, and
  2. neither of the pointers is ordered before the other according to std::less, implying that the two pointers are equal according to the total order imposed by std::less.

Is this behavior correct? Is the total order of std::less not required to be consistend with equality operator?

Is the following program allowed to output 1?

#include <iostream>
#include <set>

int main()
{
    int i=0, j=0;
    std::set<int *> s;
    s.insert(&i);
    s.insert(&j);
    std::cout << s.size() << std::endl;
}

解决方案

Seems as we have a standard breach! Panic!

Following 20.3.3/8 (C++03) :

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.

It seems a situation where eager optimizations lead to improper code...

Edit: C++0x also holds this one under 20.8.5/8

Edit 2: Curiously, as an answer to the second question:

Following 5.10/1 C++03:

Two pointers of the same type compare equal if and only if they are both null, both point to the same function, or both represent the same address

Something is wrong here... on many levels.

这篇关于std :: less必须与指针类型的相等运算符一致吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆