c++ - 带有 std::map<T*, U> 的程序是否具有明确定义的行为?

标签 c++ sorting pointers language-lawyer strict-weak-ordering

这个问题在这里已经有了答案:





Is is valid to construct std::set of pointer type?

(1 个回答)


去年关闭。




Comparing pointers to unrelated objects has unspecified results.

这似乎表明该程序可能具有未定义的行为,至少因为我们不能保证键类型的严格弱排序:

#include <map>

int main()
{
    int x = 0, y = 1;
    bool arbitrary = false;

    std::map<int*, bool> m{
       {&x, arbitrary},
       {&y, arbitrary}
    };
}

更一般地说,我们可以说带有指针键的映射是一个危险的*命题吗?或者有什么特别的规则我们可以依靠?

* 从学术上讲,即;实际上,我不知道主流实现实际上会在比较任意指针时引发 hell 。

最佳答案

是的,因为 std::map 默认比较运算符是 std::less ,与标准比较运算符不同,它完全是为指针类型定义的。

[comparisons#2]

For templates less, greater, less_­equal, and greater_­equal, the specializations for any pointer type yield a result consistent with the implementation-defined strict total order over pointers ([defns.order.ptr]).



实现定义的严格指针全序定义在 [defns.order.ptr] 中。作为:

implementation-defined strict total ordering over all pointer values such that the ordering is consistent with the partial order imposed by the builtin operators <, >, <=, >=, and <=>

关于c++ - 带有 std::map<T*, U> 的程序是否具有明确定义的行为?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59603086/

相关文章:

JavaScript - 根据特殊顺序按属性对对象数组进行排序

java - 如何按频率对单词进行排序

javascript - 是否有任何解决方法可以使 Chrome 正确排序?

c++ - 链接时 D3DCompileFromFile 未解析的外部

c++ - 链表不会打印最大值

c++ - vector::push_back 和访问 C++ 中 Vector Pointer 中的值

pointers - R 中指针的解决方法?

c - 初始化结构体数组 - C

c++ - 为多线程环境实现单例的内存泄漏

c++ - 遍历对象列表