What is the reason behind cbegin/cend?(cbegin/cend 背后的原因是什么?)
问题描述
我想知道为什么在 C++11 中引入了 cbegin 和 cend ?
I wonder why cbegin and cend were introduced in C++11?
在哪些情况下调用这些方法与 begin 和 end 的 const 重载有区别?
What are cases when calling these methods makes a difference from const overloads of begin and end?
推荐答案
很简单.假设我有一个向量:
It's quite simple. Say I have a vector:
std::vector<int> vec;
我用一些数据填充它.然后我想得到一些迭代器.也许让他们四处走动.也许到 std::for_each:
I fill it with some data. Then I want to get some iterators to it. Maybe pass them around. Maybe to std::for_each:
std::for_each(vec.begin(), vec.end(), SomeFunctor());
在 C++03 中,SomeFunctor 可以自由地修改它获得的参数.当然,SomeFunctor 可以按值或按const& 获取其参数,但没有办法确保 这样做.并非没有做这样愚蠢的事情:
In C++03, SomeFunctor was free to be able to modify the parameter it gets. Sure, SomeFunctor could take its parameter by value or by const&, but there's no way to ensure that it does. Not without doing something silly like this:
const std::vector<int> &vec_ref = vec;
std::for_each(vec_ref.begin(), vec_ref.end(), SomeFunctor());
现在,我们介绍cbegin/cend:
std::for_each(vec.cbegin(), vec.cend(), SomeFunctor());
现在,我们有句法保证,即 SomeFunctor 不能修改向量的元素(当然,没有 const-cast).我们明确地得到 const_iterator,因此 SomeFunctor::operator() 将被 const int & 调用.如果它的参数是int &,C++会报编译错误.
Now, we have syntactic assurances that SomeFunctor cannot modify the elements of the vector (without a const-cast, of course). We explicitly get const_iterators, and therefore SomeFunctor::operator() will be called with const int &. If it takes it's parameters as int &, C++ will issue a compiler error.
C++17 对此问题有更优雅的解决方案:std::as_const.好吧,至少在使用基于范围的 for 时它很优雅:
C++17 has a more elegant solution to this problem: std::as_const. Well, at least it's elegant when using range-based for:
for(auto &item : std::as_const(vec))
这只是返回一个 const& 给它提供的对象.
This simply returns a const& to the object it is provided.
这篇关于cbegin/cend 背后的原因是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:cbegin/cend 背后的原因是什么?
基础教程推荐
- c++ STL设置差异 2022-01-01
- 如何在 C++ 中正确使用命名空间? 2022-01-01
- 如何部分禁用 cmake C/C++ 自定义编译器检查 2021-01-01
- 为什么我们不能使用“虚拟继承"?在 COM 中? 2022-01-01
- 如何更改 SysDateTimePick32 或 CDateTimeCtrl 的背景颜色? 2022-01-01
- 与 CAS 的原子交换(使用 gcc 同步内置函数) 2022-01-01
- 提升 ASIO 流缓冲 2021-01-01
- 随机插入/删除的综合向量与链表基准 2022-01-01
- 将不可复制的闭包对象传递给 std::function 参数 2021-01-01
- C++:获取传递给函数的多维数组的行大小 2021-01-01
