Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fixed-size std::span vs std::array

C++20 includes std::span, which "describes an object that can refer to a contiguous sequence of objects with the first element of the sequence at position zero". Its interface is very close to std::array, though it supports dynamic extent as well as fixed one.

The obvious difference is that std::array owns its elements (and so its destructor destroys them) and std::span doesn't.

Is there anything else array can be used for that span can't?

like image 807
Alexey Romanov Avatar asked Jun 05 '18 14:06

Alexey Romanov


People also ask

Is std :: array fixed size?

std::array is a container that encapsulates fixed size arrays. This container is an aggregate type with the same semantics as a struct holding a C-style array T[N] as its only non-static data member. Unlike a C-style array, it doesn't decay to T* automatically.

Should you use std :: array?

You should not notice any difference in runtime performance while you still get to enjoy the extra features. Using std::array instead of int[] style arrays is a good idea if you have C++11 or boost at hand.

Why is std :: array more efficient than std::vector if you know the number of elements you need?

Difference between std::vector and std::array in C++ Vector is dynamic in nature so, size increases with insertion of elements. As array is fixed size, once initialized can't be resized. Vector occupies more memory. Array is memory efficient data structure.

What is a std :: span?

The class template span describes an object that can refer to a contiguous sequence of objects with the first element of the sequence at position zero. A span can either have a static extent, in which case the number of elements in the sequence is known at compile-time and encoded in the type, or a dynamic extent.


1 Answers

span is to array as pointers are to values.

Is there anything an int can be used for than an int* cannot?

If you swept your code base and replaced every int with an int* you'd have a completely nonsense codebase, even if you added a * at every point-of-use of the int*. If you swept your code base and replaced every std::array with a std::span, the same would be true.

Pointers and values are different things. You can jump through hoops and try to deal with pointers as if they are the value of the thing they point to, but trying to do so is often difficult, and the result is often incoherent.

like image 101
Yakk - Adam Nevraumont Avatar answered Oct 12 '22 20:10

Yakk - Adam Nevraumont