这个问题在这里已经有了答案:
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
,与标准比较运算符不同,它完全是为指针类型定义的。
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/