From c02ddae4bcff82b17826fe3127e835f5aa54b485 Mon Sep 17 00:00:00 2001 From: Dave Hill Date: Mon, 5 Nov 2018 15:39:41 -0800 Subject: [PATCH] Span can be constructed from empty std::array safely (#686) * Span std::array c'tor uses arr.data() instead of &arr[0] - Fixes runtime issues when constructing from an empty std::array * Construct span with std::data if C++17 detected * Specialize span c'tor for std::array of length 0, set storage to nullptr --- include/gsl/span | 28 +++++++++++++++++++--------- tests/span_tests.cpp | 8 +++++++- 2 files changed, 26 insertions(+), 10 deletions(-) diff --git a/include/gsl/span b/include/gsl/span index 8cb3dbe..b356ee9 100644 --- a/include/gsl/span +++ b/include/gsl/span @@ -394,17 +394,27 @@ public: : storage_(KnownNotNull{std::addressof(arr[0])}, details::extent_type()) {} - template > - // GSL_SUPPRESS(bounds.4) // NO-FORMAT: attribute // TODO: parser bug - constexpr span(std::array& arr) noexcept - : storage_(arr.data(), details::extent_type()) - {} + template 0)>> + constexpr span(std::array, N>& arr) noexcept + : storage_(KnownNotNull{arr.data()}, details::extent_type()) + { + } - template - // GSL_SUPPRESS(bounds.4) // NO-FORMAT: attribute // TODO: parser bug + constexpr span(std::array, 0>&) noexcept + : storage_(static_cast(nullptr), details::extent_type<0>()) + { + } + + template 0)>> constexpr span(const std::array, N>& arr) noexcept - : storage_(arr.data(), details::extent_type()) - {} + : storage_(KnownNotNull{arr.data()}, details::extent_type()) + { + } + + constexpr span(const std::array, 0>&) noexcept + : storage_(static_cast(nullptr), details::extent_type<0>()) + { + } // NB: the SFINAE here uses .data() as a incomplete/imperfect proxy for the requirement // on Container to be a contiguous sequence container. diff --git a/tests/span_tests.cpp b/tests/span_tests.cpp index 07a59c8..b38b4eb 100644 --- a/tests/span_tests.cpp +++ b/tests/span_tests.cpp @@ -452,7 +452,13 @@ TEST_CASE("from_std_array_constructor") CHECK((cs.size() == narrow_cast(arr.size()) && cs.data() == arr.data())); } - std::array ao_arr{}; + { + std::array empty_arr{}; + span s{empty_arr}; + CHECK((s.size() == 0 && s.empty())); + } + + std::array ao_arr{}; { span fs{ao_arr};