C ++ sizeof Vector是24? [英] C++ sizeof Vector is 24?

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

问题描述

我只是搞乱和学习关于向量以及结构,一度,我试图输出一个向量的大小以字节为单位。这里是代码:

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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆