5

I have a const z* zs = nullptr;

I want to convert zs to std::span

When I try to do std::span<const z>(zs) I get an error saying

error: no matching function for call to ‘std::span::span(const z* const&)’

How do I convert to zs to std::span

I tried std::span<const z>(zs[0]) it seems to compile. Is that way correct?

  • 6
    How do you expect a `span` over `nullptr` to behave? This seems broken by design. – Fureeish Sep 17 '20 at 08:08
  • Dereferencing a null pointer (which is sort of what you are trying to do `*(zs + 0)` where `zs = nullptr`) is undefined behavior. That's why you have no error from the compiler. – Roy2511 Sep 17 '20 at 08:10
  • The error message is straightforward: you can't construct a span given only a pointer value. It wouldn't matter if it pointed at a valid element rather than being `nullptr` - the problem is that a span has to know how many elements to span over. Pointers, by design, do not store any such information. The question is, *why* do you want to do this conversion? If you simply want to have a zero-length span, then there is no reason to set up a pointer in the first place. – Karl Knechtel Sep 17 '20 at 08:16

2 Answers2

5

std::span has a constructor which takes a pointer and a size, use that:

std::span<const z>(zs, 0)

Mestkon
  • 3,532
  • 7
  • 18
2

You need to provide a length to go along with your pointer. A null pointer points to 0 elements. Are you reassigning sz somewhere?

An empty span is constructed from no arguments.

std::span<const z>{}
Caleth
  • 52,200
  • 2
  • 44
  • 75