Main Content

AUTOSAR C++14 Rule A18-1-2

The std::vector<bool> specialization shall not be used

Description

Rule Definition

The std::vector<bool> specialization shall not be used.

Rationale

The specialization of std::vector for the type bool can be made space-efficient in an implementation defined manner. For instance, std::vector<bool> does not necessarily store its elements as a contiguous array. As a result, the specialization does not work as expected with all standard library template (STL) algorithms, such as the index operator[]() which does not return a contiguous sequence of elements. You cannot safely modify distinct elements of STL container std::vector<bool>.

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>

class BoolWrapper
{
public:
    BoolWrapper() = default;
    constexpr BoolWrapper(bool b) : b_(b) {}
    constexpr operator bool() const
    {
        return b_;
    }
private:
    bool b_{};
};

void Fn() noexcept
{
    std::vector<bool> v2; //non-compliant
    std::vector<BoolWrapper> v3{true, false, true, false}; //compliant
}

In this example, vector v2 is non-compliant because it is declared with std::vector<bool>. A possible fix is to use std::vector with a value type BoolWrapper that wraps bool.

Check Information

Group: 18 Language Support Library
Category: Required, Automated

Version History

Introduced in R2019b