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?
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With