Convert a nullptr to std::span
Asked Answered
D

2

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?

Dysgenic answered 17/9, 2020 at 8:4 Comment(3)
How do you expect a span over nullptr to behave? This seems broken by design.Synesthesia
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.Snorkel
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.Tarsia
N
6

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

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

Nuncio answered 17/9, 2020 at 8:24 Comment(0)
M
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>{}
Mccallum answered 17/9, 2020 at 8:10 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.