《Effective Modern C++》学习笔记之条款十三:优先选用const_iterator,而非iterator

在C++98中 const_iterator得到的支持不够全面,使用起来相当费力,C++11对其做了一个很大的优化,但是仍然有死角,但是C++14将这些死角清除干净了,所以现在我们可以很好的使用它。

首先我们要记住的是在C++11中无法将iterator强制转换为const_iterator,即使是static_cast或者reinterpret_cast也不行。

如果我们要获取const_iterator类型迭代器,在C++11中很简单,只需要使用对象调用其成员函数cbegin()或cend()即可。但是这里请注意,C++11只提供了成员函数版本的cbegin()及cend(),而没有实现非成员版本的,当然这一点已经在C++14中得到解决。在C++11中我们也可以自己实现:

template <class T>
auto cbegin(const T& c) ->decltype(std::begin(c)) {
    return std::begin(c);
}

要点速记

  • 优先选用const_iterator,而非iterator
  • 在最通用的代码中,优先选用非成员函数版本的begin()、end()、cbegin()、cend()等

猜你喜欢

转载自blog.csdn.net/Chiang2018/article/details/114240756
今日推荐