C++ sizeof Vector 是 24?

2021-12-21 00:00:00 vector c++

我只是在胡闹,学习向量和结构体,有一次,我尝试以字节为单位输出向量的大小.代码如下:

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;
}

输出为244.

显然第二行打印了 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 位体系结构上,每个指针的大小为 8 个字节;因此您有 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:

  • 向量开始
  • 向量结束
  • 为向量保留的内存结束(即向量的容量)

相关文章