问题描述
我只是搞乱和学习关于向量以及结构,一度,我试图输出一个向量的大小以字节为单位。这里是代码:
I was just messing around and learning about vectors as well as structs, and at one point, I tried outputting the size of a vector in bytes. Here's the code:
#include <iostream>
#include <vector>
struct Foo{
std::vector<int> a;
};
int main()
{
using std::cout; using std::endl;
Foo* f1 = new Foo;
f1->a.push_back(5);
cout << sizeof(f1->a) << endl;
cout << sizeof(f1->a[0]) << endl;
delete[] f1;
}
输出 24
和 4
。
显然第二行打印4,因为这是一个int的大小。但是为什么另一个值是24?向量占用24字节的内存吗?谢谢!
Obviously the second line printed 4, because that is the size of an int. But why exactly is the other value 24? Does a vector take up 24 bytes of memory? Thanks!
推荐答案
虽然 std :: vector
由标准定义,可以有不同的实现:换句话说, std :: vector
下可以从实现改为实现。
While the public interface of std::vector
is defined by the standard, there can be different implementations: in other words, what's under the hood of std::vector
can change from implementation to implementation.
即使在相同的实现中(例如:Visual C ++的给定版本附带的STL实现), std: :vector
可以从发布版本和调试版本中进行更改。
Even in the same implementation (for example: the STL implementation that comes with a given version of Visual C++), the internals of std::vector
can change from release builds and debug builds.
你看到的24个大小可以解释为3个指针在64位体系结构上的大小;因此您有3 x 8 = 24字节)。这些指针可以是:
The 24 size you see can be explained as 3 pointers (each pointer is 8 bytes in size on 64-bit architectures; so you have 3 x 8 = 24 bytes). These pointers can be:
- 向量开头
- 向量结尾
- 向量的保留内存结尾(即向量的容量)
- begin of vector
- end of vector
- end of reserved memory for vector (i.e. vector's capacity)
这篇关于C ++ sizeof Vector是24?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!