I wonder why cbegin and cend were introduced in C++11?
What are cases when calling these methods makes a difference from const overloads of begin and end?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
It’s quite simple. Say I have a vector:
I fill it with some data. Then I want to get some iterators to it. Maybe pass them around. Maybe to
std::for_each:In C++03,
SomeFunctorwas free to be able to modify the parameter it gets. Sure,SomeFunctorcould take its parameter by value or byconst&, but there’s no way to ensure that it does. Not without doing something silly like this:Now, we introduce
cbegin/cend:Now, we have syntactic assurances that
SomeFunctorcannot modify the elements of the vector (without a const-cast, of course). We explicitly getconst_iterators, and thereforeSomeFunctor::operator()will be called withconst int &. If it takes it’s parameters asint &, C++ will issue a compiler error.C++17 has a more elegant solution to this problem:
std::as_const. Well, at least it’s elegant when using range-basedfor:This simply returns a
const&to the object it is provided.