Main Content

AUTOSAR C++14 Rule A23-0-1

An iterator shall not be implicitly converted to const_iterator

Since R2020a

Description

Rule Definition

An iterator shall not be implicitly converted to const_iterator.

Rationale

The C++11 standard introduces member functions such as cbegin and cend that returns const iterators to containers. To create const iterators, use these member functions instead of functions such as begin and end that return non-const iterators and then require implicit conversions.

For instance, consider the std::list container:

std::list<int> aList = {0, 0, 1, 2};
You can use the begin and end member functions of the container to create const iterators, for instance in a for loop:
for(std::vector<int>::const_iterator iter{aList.begin()}, end{aList.end()};
    iter != end;
    ++iter) {...}
However, the functions begin and end return non-const iterators and for assignment to the const iterators iter and end respectively, an implicit conversion must happen. Instead, take advantage of the new C++11 functions cbegin and cend that directly returns const iterators:
for(std::vector<int>::const_iterator iter{aList.cbegin()}, end{aList.cend()};
    iter != end;
    ++iter) {...}
If you use these functions, you can also replace the explicit type specification of the iterators with auto:
for(auto iter{aList.cbegin()}, end{aList.cend()};
    iter != end;
    ++iter) {...}

Polyspace Implementation

The checker flags conversions from type iterator to const_iterator or reverse_iterator to const_reverse_iterator.

Troubleshooting

If you expect a rule violation but Polyspace® does not report it, see Diagnose Why Coding Standard Violations Do Not Appear as Expected.

Examples

expand all

#include <cstdint>
#include <vector>

void func(std::vector<int32_t> & values, int32_t aValue) {
    std::vector<int32_t>::const_iterator iter1 = 
                  std::find(values.begin(), values.end(), aValue); //Noncompliant
    std::vector<int32_t>::const_iterator iter2 = 
                  std::find(values.cbegin(), values.cend(), aValue);  //Compliant
}

In this example, the first std::find function call uses as arguments the return values of the begin and end methods of an std::vector container values. These methods return iterators of type std::vector<intr32_t>::iterator. Since the std::find template has the same return type as the types of the first two arguments, it also returns an iterator of type std::vector<intr32_t>::iterator. The return value is assigned to a variable of type std::vector<intr32_t>::const_iterator, resulting in an implicit conversion.

The second call uses the cbegin and cend methods which return iterators of type std::vector<intr32_t>::const_iterator and avoid the implicit conversion.

Check Information

Group: Containers library
Category: Required, Automated

Version History

Introduced in R2020a