Rule A18-1-1 (required, implementation, automated)

C-style arrays shall not be used.

Rationale

A C-style array is implicitly convertible to a raw pointer and easily loses information about its size. This construct is unsafe, unmaintainable, and a source of potential errors. For fixed-size, stack-allocated arrays, std::array is supposed to be used instead. This type is designed to work with standard library algorithms.

Exception

It is allowed to declare a static constexpr data member of a C-style array type.

Example

// $Id: A18-1-1.cpp 289436 2017-10-04 10:45:23Z michal.szczepankiewicz $
#include <algorithm>
#include <array>
#include <cstdint>
void Fn() noexcept
{
const std::uint8_t size = 10;
std::int32_t a1[size];
// Non-compliant
std::array<std::int32_t, size> a2; // Compliant
// ...
std::sort(a1, a1 + size);
std::sort(a2.begin(), a2.end()); // More readable and maintainable way of
// working with STL algorithms
}
class A
{
public:

static constexpr std::uint8_t array[]{0, 1, 2}; // Compliant by exception
};

See also

C++ Core Guidelines [11]: ES.27: Use std::array or stack_array for arrays on the stack. C++ Core Guidelines [11]: SL.con.1: Prefer using STL array or vector instead of a C array. Rule A18-1-2 (required, implementation, automated) The std::vector specialization shall not be used.

Rationale

The std::vector specialization does not work with all STL algorithms as expected. In particular, operator does not return a contiguous sequence of elements as it does for the primary template std::vector. The C++ Language Standard guarantees that distinct elements of an STL container can be safely modified concurrently, except when the container is a std::vector< bool>. Note that std::bitset, std::array<bool, N>, std::deque, or using std::vector with a value type which wraps bool are possible alternatives.

Example

// $Id: A18-1-2.cpp 312108 2018-03-16 17:56:49Z jan.babst $
#include <cstdint>
#include <vector>

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

// implicit by design
// implicit by design

void Fn() noexcept
{
std::vector<std::uint8_t> v1;
std::vector<bool> v2;
std::vector<BoolWrapper> v3{true, false, true, false}; // Compliant
}

// Compliant
// Non-compliant

See also

HIC++ v4.0 [9]: 17.1.1: Do not use std::vector.