Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simplest way to get memory size of std::array's underlying array?

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.

like image 911
NPS Avatar asked Sep 27 '17 13:09

NPS


3 Answers

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 array T[N] as its only non-static data member.

like image 196
Vittorio Romeo Avatar answered Oct 20 '22 18:10

Vittorio Romeo


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.

like image 3
MSalters Avatar answered Oct 20 '22 18:10

MSalters


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.

like image 2
NPS Avatar answered Oct 20 '22 19:10

NPS