Understanding the space occupied by an vector instance in C++

偶尔善良 提交于 2019-12-13 05:47:50

问题


I'm trying to understand the amount of bytes occupied by an instance of std::vector. The following code:

    vector <int>uno;
    uno.push_back(1);
    uno.push_back(1);
    cout <<"1: "<< sizeof(uno)<<" bytes"<<endl;
    cout << endl;

    vector <bool>unos;
    unos.push_back(true);
    cout <<"2: "<< sizeof(unos)<<" bytes"<<endl;
    cout << endl;

gives me this output:

1: 12 bytes

2: 20 bytes

Can someone explain me why the size of the vector<bool> has more bytes than the vector<int>?. And what is the correct way to measure the size in bytes of an vector instance... by adding the size of every member in the vector?


回答1:


In C++, the sizeof operator is always evaluated at compile time, so every vector<T> will have the same size (unless vector<T> is a specialization like vector<bool>).

In case you are wondering about the 12 bytes, that is probably the size of 3 pointers, or alternatively, the size of a pointer and an element count and a capacity. The real data is never stored inside the vector.

If you want to know how much memory is used total, a good approximation is:

sizeof(std::vector<T>) + my_vector.capacity() * sizeof(T)

This is only an approximation because it does not take into account book-keeping data on the heap.




回答2:


std::vector<bool> is larger since it is more complicated than std::vector<int>. The current C++ standard specifies that the vector<bool> data should be bit-packed. This requires some additional bookkeeping, and gives them a slightly different behavior than the normal std::vector<T>.

This different behavior of std::vector<bool> is very likely to be removed in the upcoming C++0x standard.



来源:https://stackoverflow.com/questions/4421698/understanding-the-space-occupied-by-an-vector-instance-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!