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

What is the reason behind cbegin/cend?(cbegin/cend 背后的原因是什么?)
本文介绍了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.

这篇关于cbegin/cend 背后的原因是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Rising edge interrupt triggering multiple times on STM32 Nucleo(在STM32 Nucleo上多次触发上升沿中断)
How to use va_list correctly in a sequence of wrapper functions calls?(如何在一系列包装函数调用中正确使用 va_list?)
OpenGL Perspective Projection Clipping Polygon with Vertex Outside Frustum = Wrong texture mapping?(OpenGL透视投影裁剪多边形,顶点在视锥外=错误的纹理映射?)
How does one properly deserialize a byte array back into an object in C++?(如何正确地将字节数组反序列化回 C++ 中的对象?)
What free tiniest flash file system could you advice for embedded system?(您可以为嵌入式系统推荐什么免费的最小闪存文件系统?)
Volatile member variables vs. volatile object?(易失性成员变量与易失性对象?)