Search code examples
c++visual-studiovisual-c++static-analysiscpp-core-guidelines

How to handle static analysis warning from Core Guidelines checker about gsl::at?


I activated static analysis for my project in Visual Studio. The Core Guidelines checker says i should use gsl::at for subscription. But my code is save. What's the cleanest way to get rid of this warning? Should I disable it? Should I write my code differently? Should I use gsl::at introducing an overhead for the check? My code is:

template <typename T, size_t N>
void increase(T(&data)[N])
{
    for (size_t i = 0; i < N; ++i)
        data[i] +=1;
}

Solution

  • I found a solution myself. Because the size is known at compile time, it is possible to use a std::array, std::get and std::index_sequence. std::get leads to a compilation error if the index is out of bounds. There is no longer a need for a runtime check.

    template <typename... Ts>
    constexpr void noop(Ts...) noexcept {}
    
    template <typename T, size_t N, size_t... I>
    constexpr void increase(std::array<T, N>& data, std::index_sequence<I...>) noexcept
    {
        noop((std::get<I>(data) += 1)...);
    }
    
    template <typename T, size_t N>
    constexpr void increase(std::array<T, N>& data) noexcept
    {
        increase(data, std::make_index_sequence<N>{});
    }