C++ sizeof Vector 是 24?

时间:2023-05-09
本文介绍了C++ sizeof Vector 是 24?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

限时送ChatGPT账号..

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

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:

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

这篇关于C++ sizeof Vector 是 24?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

上一篇:如果增加一个等于 STL 容器的结束迭代器的迭代器会发生什么 下一篇:sizeof() 一个向量

相关文章