Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 641
Garrett Yates Avatar asked Sep 03 '25 10:09

Garrett Yates


1 Answers

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.

like image 162
L. F. Avatar answered Sep 04 '25 23:09

L. F.