Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Size of struct with vector

I am trying to find the difference in size from a struct with vector of object and struct with a vector of object pointers.

The code I have written shows that size of the both structs are the same even in theory at least based their content they should be different.

What would be the correct way of finding the correct size of a struct based on it's contents?

#include <iostream>
#include <string>
#include <vector>
using namespace std;

struct Song{
    string Name;
    string Artist;
};

struct Folder{
    vector<Song*> list;
};

struct Library{
    vector<Song> songs;
};

int main(int argc, const char * argv[]) {

    Library library;
    Folder favorites;
    Folder recentPurchaces;

    library.songs.push_back(Song{"Human After All", "Daft Punk"});
    library.songs.push_back(Song{"All of my love", "Led Zepplin"});


    favorites.list.push_back(&library.songs[0]);
    favorites.list.push_back(&library.songs[2]);


    cout << "Size of library: " << sizeof(library) << endl;
    cout << "Size of favorites: " << sizeof(favorites) << endl;



    return 0;
}
like image 858
user1721803 Avatar asked Jan 09 '23 19:01

user1721803


1 Answers

in theory at least based their content they should be different.

No, the sizes shouldn't be different: std::vector<T> stores the data in dynamically allocated storage, while the struct stores only the "anchor" part, consisting of a couple of pointers. The number of items inside the vectors, as well as the size of the items inside the vector itself, are not counted in determining the size of this footprint.

In order to compute the size in memory you need to write a function that adds up sizes of the individual items inside each container, and add the capacity of a container itself, times the size of a container item.

like image 118
Sergey Kalinichenko Avatar answered Jan 22 '23 12:01

Sergey Kalinichenko