C++ sizeof Vector 是 24?

C++ sizeof Vector is 24?(C++ sizeof Vector 是 24?)
本文介绍了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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

OpenGL transforming objects with multiple rotations of Different axis(OpenGL 变换不同轴多次旋转的对象)
GLFW first responder error(GLFW 第一响应者错误)
SOIL not linking correctly(SOIL 连接不正确)
Core profile vs version string? Only getting GLSL 1.3/OGL 3.0 in mesa 10.0.1(核心配置文件与版本字符串?在 mesa 10.0.1 中只获得 GLSL 1.3/OGL 3.0)
What is the range of OpenGL texture ID?(OpenGL 纹理 ID 的范围是多少?)
How taxing are OpenGL glDrawElements() calls compared to basic logic code?(与基本逻辑代码相比,OpenGL glDrawElements() 调用的繁重程度如何?)