Search code examples
c++arraysstringsize

Memory efficiency of C++ arrays


Somewhere in my brainstem a voice whispers:

In C++, an array does not need more memory than the number of elements need.

std::string str = "aabbcc"; 
std::array<std::string, 3> str_array = {"aa", "bb", "cc"}; 

Accordingly, both should have the same size, because (unlike in Java), there is no separate size field or similar. But I haven't found a reference.

Is this true? Under which circumstances is it not?


Solution

  • In C++, an array does not need more memory than the number of elements need.

    This is true. A raw array has a size equal to the size of it's element type times the number of elements. So,

    int array[10];
    

    has a size of sizeof(int) * std::size(array). std::array is the same but it is allowed to have padding so

    std::array<int, 10> array;
    

    has the size of sizeof(int) * std::size(array) + P where P is some integer amount of padding.

    Your example though isn't quite the same thing.
    A std::string is a container. It has it's own size that is separate of what it contains. So sizeof(std::string) will always be the same thing regardless of how many characters are in the string. So ignoring short string optimization

    std::string str = "aabbcc"; 
    

    Takes of sizeof(std::string) plus however much the string allocated for the underlying c-string. That is not the same value as

    std::array<std::string, 3> str_array = {"aa", "bb", "cc"};
    

    Since you now have 3 * sizeof(std::string) plus whatever each string allocated.