L. *_* F. 5 c++ const c++20 std-span
标准容器传播const。也就是说,如果容器本身是const,则它们的元素自动为const。例如:
const std::vector vec{3, 1, 4, 1, 5, 9, 2, 6};
ranges::fill(vec, 314); // impossible
const std::list lst{2, 7, 1, 8, 2, 8, 1, 8};
ranges::fill(lst, 272); // impossible
Run Code Online (Sandbox Code Playgroud)
内置数组还传播const:
const int arr[] {1, 4, 1, 4, 2, 1, 3, 5};
ranges::fill(arr, 141); // impossible
Run Code Online (Sandbox Code Playgroud)
但是,我注意到std::span(大概)不会传播const。最小的可重现示例:
#include <algorithm>
#include <cassert>
#include <span>
namespace ranges = std::ranges;
int main()
{
int arr[] {1, 7, 3, 2, 0, 5, 0, 8};
const std::span spn{arr};
ranges::fill(spn, 173); // this compiles
assert(ranges::count(arr, 173) == 8); // passes
}
Run Code Online (Sandbox Code Playgroud)
为什么此代码可以正常工作?为什么std::span将const与标准容器区别对待?
想想指针。指针也不传播 const。指针的常量性与元素类型的常量性无关。
考虑修改后的最小可重复示例:
#include <algorithm>
#include <cassert>
#include <span>
namespace ranges = std::ranges;
int main()
{
int var = 42;
int* const ptr{&var};
ranges::fill_n(ptr, 1, 84); // this also compiles
assert(var == 84); // passes
}
Run Code Online (Sandbox Code Playgroud)
它的设计是std::span一种指向连续元素序列的指针。根据[span.iterators]:
Run Code Online (Sandbox Code Playgroud)constexpr iterator begin() const noexcept; constexpr iterator end() const noexcept;
请注意,无论 Span 本身是否为 const,都会返回一个非常量迭代器begin()。end()因此,std::span不会以类似于指针的方式传播 const。跨度的常量与元素类型的常量无关。
const 1 std::span< const 2元素类型,范围>
第一个const指定跨度本身的常量性。第二个const指定元素的常量。换句话说:
std::span< T> // non-const span of non-const elements
std::span<const T> // non-const span of const elements
const std::span< T> // const span of non-const elements
const std::span<const T> // const span of const elements
Run Code Online (Sandbox Code Playgroud)
spn如果我们将示例中的声明更改为:
std::span<const int, 8> spn{arr};
Run Code Online (Sandbox Code Playgroud)
代码无法编译,就像标准容器一样。spn在这方面,你是否将自己标记为 const 并不重要。spn = another_arr(但是,如果将其标记为 const,则不能执行类似的操作)
(注意:您仍然可以在以下命令的帮助下使用类模板参数推导std::as_const:
std::span spn{std::as_const(arr)};
Run Code Online (Sandbox Code Playgroud)
只是不要忘记#include <utility>。)
span实际上,将const传播为类似的类型并没有多大意义,因为它无论如何也无法保护您免受任何伤害。
考虑:
void foo(std::span<int> const& s) {
// let's say we want this to be ill-formed
// that is, s[0] gives a int const& which
// wouldn't be assignable
s[0] = 42;
// now, consider what this does
std::span<int> t = s;
// and this
t[0] = 42;
}
Run Code Online (Sandbox Code Playgroud)
即使s[0]给了int const&,也t[0]一定给了int&。并t指与完全相同的元素s。毕竟,它是一个副本,并且span不拥有其元素-它是引用类型。即使s[0] = 42失败,std::span(s)[0] = 42也会成功。这种限制对任何人都没有好处。
与常规容器(例如vector)的不同之处在于,此处的副本仍然引用相同的元素,而复制a vector会为您提供全新的元素。
有方式span是指一成不变的元素是不是让span自己const,它使底层元素本身const。即:span<T const>,不是span<T> const。