Garrett Yates
Garrett Yates

Reputation: 49

Can I return a span in C++? If so, how? (Open to alternatives.)

The project guide for an assignment I've been given specifically barred the use of vectors and strings, but I need to pass a char array of indeterminate size from a function. The use of span seems like it might be viable for this purpose if I can better understand how it is used. If anyone could recommend a better/different means of passing arrays (aside from strings and vectors) I would love to learn about it.

I have considered generating a scratch file and storing input text there for recall elsewhere in the program, but that seems rather more cumbersome than should be necessary in this case. This program will also be small enough that I could do everything in main, but that also shouldn't be necessary.

What I would like to do is to be able to call a function like this:

span<char> getSpan(){
    char arr[] = { 'A', 'B', 'C' };
    span<char> spanOut{ arr };
    return spanOut;
}

and then print the contents of spanOut from main:

int main() {
    // Some Code...
    printSpan = getSpan();
    std::cout << printSpan;
}

Ideally, the result of the above code would be to have ABC printed to the terminal.

Upvotes: 4

Views: 3695

Answers (2)

Garrett Yates
Garrett Yates

Reputation: 49

It turns out that Anonymous Anonymous was correct, the instructor wanted me to use dynamically allocated memory. I had been getting too "clever" for my own good, and missing the obvious in favor of complexity. Thank you, L.F., for your excellent breakdown of span :)

Upvotes: 0

L. F.
L. F.

Reputation: 20589

span is a non-owning view. It is similar to pointers and references. When getSpan returns, the local array arr no longer exists. The returned span points to this nonexistent array, and accessing it results in undefined behavior. This is analogous to the dangling pointer problem.

You can return a span if you make sure that the storage still exists after the function returns:

auto getSpan()
{
    static char arr[] = { 'A', 'B', 'C' }; // note: static
    return span(arr);
}

Note that this problem is present as long as you return something with pointer semantics (i.e., non-owning) — iterators, references, etc.

Upvotes: 2

Related Questions