void foo(const auto& collection)
{
*collection.begin() = 104;
}
int main()
{
std::vector<int> ints {1, 2, 3, 4, 5};
foo(ints); // Error, as it should be
foo(ints | std::views::all); // Compiles and modifies the vector. Why?
return 0;
}
为什么如果函数参数的类型是std::view,左值引用的const性质会被完全忽略?
编辑:
如果像您在评论中所写的那样,const view 引用在这个上下文中类似于 const 指针,为什么如果同一个函数以 rvalue 对象构造的视图作为参数,代码无法编译?
std::vector<int> getVec()
{
return std::vector{1, 2, 3, 4, 5};
}
void foo(const auto& collection)
{
*collection.begin() = 104; // Error: assignment of read-only location
}
int main()
{
foo(getVec() | std::views::all); // Nope!
return 0;
}
const std::span<int>
和std::span<const int>
没有区别。 - Chris_Fint *p;
,对它的const
引用仍然允许你修改*p
。 - Sam Varshavchikconst
是浅层的,它不是传递性的。(我希望有一个传递性的deep_const
。) - Eljaypropagate_const
。 - starball