How should I represent a contiguous sequence of elements I own?

82 Views Asked by At

I have a bunch of typed data in consecutive memory that I got as a T *; and I also know the number of elements (as a std::size_t although it doesn't matter much).

I'd like to use some single type or data structure to represent my stretch of typed data.

Now, what I have is the information for constructing...

  • A gsl::span<T>, but with ownership.
  • A gsl::owner<T *>, but with a size.

What type/structure/container would I use to represent all of my information about this data?

Notes:

  • Obviously I'm ok with using GSL constructs; stuff in C++2a or Boost is also fine.
  • I was thinking of a chimera of owner and span - perhaps gsl::owner<gsl::span<T>>; but I don't really like this idea too much.
1

There are 1 best solutions below

1
Caleth On

You could inherit gsl::span<T> and hold a std::unique_ptr<T[]>

template <typename T, typename D = std::default_delete<T>>
struct owning_span : public gsl::span<T>
{
    owning_span() {}
    owning_span(T* ptr, index_type size, D d = {}) : span(ptr, size), m_ptr(ptr, std::move(d)) {}
    owning_span(T* first, T* last, D d = {}) : span(first, last), m_ptr(first, std::move(d)) {}
    // other constructors ?
private:
    std::unique_ptr<T[], D> m_ptr;
};

One note: you can still copy construct / assign gsl::spans from this, slicing off the ownership. Not sure if that is a pro or a con