【问题标题】:Fixed-size std::span vs std::array固定大小的 std::span 与 std::array
【发布时间】:2018-06-05 14:02:29
【问题描述】:

C++20 包括std::span, which "describes an object that can refer to a contiguous sequence of objects with the first element of the sequence at position zero"。它的界面非常接近std::array,虽然它支持动态范围以及固定范围。

明显的区别在于std::array 拥有它的元素(因此它的析构函数会销毁它们)而std::span 没有。

还有什么array 可以用于span 不能用的吗?

【问题讨论】:

  • 不是跨度不同的用例吗?我可能错了,但我认为 span 就像 string_view for strings
  • Span 的原因完全不同。 Span 基本上是 C++ 动态数组的一个安全习惯用法 - 封装指向序列开始和结束的指针。
  • span 是 array 什么 string_view 它是 string。 array 可用于复制内存,而span 仅操作它的句柄。
  • “有什么int 可以用于int* 不能用的吗?”

标签: c++ stl stdarray c++20


【解决方案1】:

span 指向 array,就像指针指向值一样。

有什么int 可以使用而int* 不能使用吗?

如果您扫描您的代码库并将每个int 替换为int*,您将拥有一个完全无意义的代码库,即使您在int* 的每个使用点添加了*。如果您扫描您的代码库并将每个std::array 替换为std::span,情况也是如此。

指针和值是不同的东西。您可以跳过箍并尝试处理指针,就好像它们是它们所指向的事物的值一样,但是尝试这样做通常很困难,并且结果通常是不连贯的。

【讨论】:

    猜你喜欢
    • 2012-07-04
    • 1970-01-01
    • 2017-02-17
    • 2021-10-10
    • 2011-05-24
    • 1970-01-01
    • 2018-05-26
    • 2019-04-07
    • 2017-07-29
    相关资源
    最近更新 更多