为什么 std::span 缺少比较运算符? [英] Why does std::span lack the comparison operators?

查看:32
本文介绍了为什么 std::span 缺少比较运算符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

std::span 不是被设计为对 std::vector/std::array/普通数组之类的?它不应该在其 API 中也包含比较运算符,以与它们保持一致吗?排除背后的原因是什么?

Wasn't the std::span designed as a lightweight reference to sub-regions of std::vector/std::array/plain array and alike? Shouldn't it also contain comparison operators in its API, to be consistent with them? What was the reasoning behind the exclusion?

注意:通过比较运算符,我指的是完整集合 (<, <=, ...) 或宇宙飞船 <=>

Note: by comparison operators, I mean either the full set (<, <=, ...) or the spaceship <=>

推荐答案

正如 Daniel Langr 指出的std::span 在其最初的提案中具有比较运算符 P0122.这些运算符随后被删除,因为工作草案 N4791,原因在P1085.

As Daniel Langr pointed out, std::span has comparison operators in its initial proposal P0122. These operators are then removed since the working draft N4791, and the reasons are stated in P1085.

简而言之,std::span 的 copy 和 const 是浅的"(意味着复制 std::span 不会复制其底层元素,而const std::span 不会阻止其底层元素被修改),因此比较(如果存在)也应该是浅的"以保持一致性.

In short, copy and const for std::span are "shallow" (meaning copying a std::span doesn't copy its underlying elements, and a const std::span doesn't prevent its underlying elements from being modified), so comparisons, if exist, should also be "shallow" for consistency.

那篇论文给出了以下例子:

That paper gives the following examples:

示例 1:

T oldx = x;
change(x);
assert(oldx != x);
return oldx;

示例 2:

void read_only(const T & x);

void f()
{
  T tmp = x;
  read_only(x);
  assert(tmp == x);
}

如果T = std::span,这些示例中的断言可能会失败,而对于常规类型则不会.

The assertions in these examples may fail if T = std::span, while it doesn't for regular types.

有人可能会争辩说,std::string_view 具有浅拷贝但深比较.P1085对此也有解释:

One may argue that std::string_view has shallow copy but deep comparisons. P1085 also has an explanation for this:

这匹配string_view,但是string_view不能修改它指向的元素,因此可以认为string_view的浅拷贝类似于写时复制优化.

This matches string_view, however string_view can't modify the elements it points at, and thus the shallow copy of string_view can be thought of as similar to a copy-on-write optimization.

这篇关于为什么 std::span 缺少比较运算符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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