nop
nop

Reputation: 6341

Returning std::span from a function

Yesterday I started to use std::span because it's really handy, so I wanted to know if I'm getting std::span out of function correctly. Is it correct?

std::span<std::uint8_t const> span1;
if (read_data(&span1))
    return 0;

// function
int read_data(std::span<std::uint8_t const>* output)
{
    uint8_t* address = ...
    size_t size = ...

    *output = { address, size };

    return NO_ERROR;
}

Upvotes: 1

Views: 1265

Answers (1)

Is it correct?

A bit hard to tell when you omit the most important bit and replace it by a pair of ....

Assuming the buffer is not of automatic storage duration and persists beyond the function call... Then yes, it's not immediately wrong. But if you intend for the span to own the buffer, you'd soon get into trouble.

A span is meant to represent a non-owning reference type, like a raw pointer. Owning raw pointers are problematic in the general case, and a span would be no different.

If on the other hand you only use the span to grant a view of the buffer (and there is no lifetime issues), then it's a perfectly legitimate use of std::span. It's its intended purpose.

Upvotes: 2

Related Questions