Is this the simplest/shortest way to get size in memory of the content of what std::array::data()
returns?
arr.size() * sizeof(arr.value_type)
Edit: My question wasn't precise. By "size in memory" I mean size of all elements (themselves) contained in the array so if e.g. they are pointers pointing to structures, I want the size of the pointers alone, not the structures pointed to. I also don't want to include the size of any possible overhead of the std::arr
implementation. Just the array elements.
Some people suggested sizeof(arr)
. This: What is the sizeof std::array<char, N>? begs to disagree. And while it seems to work on my machine I want to know what the standard guarantees.
You can use the sizeof
operator directly on your std::array
instance:
sizeof(arr)
Example:
struct foo
{
int a;
char b;
};
int main()
{
std::array<foo, 10> a;
static_assert(sizeof(foo) == 8);
static_assert(sizeof(a) == 80);
}
live example on wandbox
From cppreference:
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 arrayT[N]
as its only non-static data member.
There's no guarantee that sizeof(std::array<T,N>) == N*sizeof(T)
, but it is guaranteed that sizeof(std::array<T,N>) >= N*sizeof(T)
. The extra size might be named (but unspecified) members and/or unnamed padding.
The guarantee follows from the fact that the wrapped T[N]
array must be the first member of std::array<T,N>
, but other members aren't specified.
Since no one has posted anything better than my first guess in question and sizeof(arr)
is most likely NOT guaranteed to not include the size of any possible additional std::array's
fields I'm choosing this as the accepted answer.
arr.size() * sizeof(arr.value_type)
Should anyone come up with anything better I'd be happy to accept their answer instead.
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