Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

The Zero Allocations project #18849

Closed
wants to merge 9 commits into from
Prev Previous commit
Next Next commit
Make pointer-based Span construction safer
This prevents constructing a Span<A> given two pointers into an array
of B (where B is a subclass of A), at least without explicit cast to
pointers to A.
  • Loading branch information
sipa committed May 12, 2020
commit bb3d38fc061d8482e68cd335a45c9cd8bb66a475
17 changes: 15 additions & 2 deletions src/span.h
Original file line number Diff line number Diff line change
Expand Up @@ -22,9 +22,22 @@ class Span

public:
constexpr Span() noexcept : m_data(nullptr), m_size(0) {}
constexpr Span(C* data, std::size_t size) noexcept : m_data(data), m_size(size) {}

constexpr Span(C* data, C* end) noexcept : m_data(data), m_size(end - data) {}
/** Construct a span from a begin pointer and a size.
*
* This implements a subset of the iterator-based std::span constructor in C++20,
* which is hard to implement without std::address_of.
*/
template <typename T, typename std::enable_if<std::is_convertible<T (*)[], C (*)[]>::value, int>::type = 0>
constexpr Span(T* begin, std::size_t size) noexcept : m_data(begin), m_size(size) {}

/** Construct a span from a begin and end pointer.
*
* This implements a subset of the iterator-based std::span constructor in C++20,
* which is hard to implement without std::address_of.
*/
template <typename T, typename std::enable_if<std::is_convertible<T (*)[], C (*)[]>::value, int>::type = 0>
constexpr Span(T* begin, T* end) noexcept : m_data(begin), m_size(end - begin) {}

/** Implicit conversion of spans between compatible types.
*
Expand Down