cbegin/cend 背后的原因是什么?

我想知道为什么在 C++11 中引入了 cbegincend ?

I wonder why cbegin and cend were introduced in C++11?

在哪些情况下调用这些方法与 beginend 的 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.

相关文章