问题
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