空矢量的大小 [英] Size of empty vector

查看:187
本文介绍了空矢量的大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下使用 g ++ 4.8.2 运行的程序在32位Linux系统上给出了输出12:

The following program on running with g++ 4.8.2 gave the output 12 on a 32-bit Linux system:

vector<char> v;
cout << sizeof(v) << endl;

我看到 this 并知道 sizeof(v)可能是特定于实现的。不过,我想知道是什么原因导致该向量的大小为12.我认为迭代器 v.begin() v.end()可能会贡献8个字节的大小。我对么?如果是,那剩下的4个字节的大小是什么?如果没有,这12个字节到底是什么?

I saw this and know that sizeof(v) could be implementation specific. Still, I was wondering what might be causing that vector to have a size of 12. What I think is that the iterators v.begin() and v.end() might be contributing to 8 bytes of the size. Am I correct? If yes, what is contributing to the remaining 4 bytes of size? If not, what are these 12 bytes all about?

推荐答案

看看来源。 libstdc ++ 是gcc下载的一部分。

Take a look at the sources. libstdc++ is part of the gcc download.

无论如何,容器必须有这些成员(或者等同于所有成员)指针):

Anyway, the container must have these members (or equivalent, like all pointers):


  1. 数据指针, char * 的4个字节。

  2. 元素计数或结束指针, size_t char *

  3. 缓冲区大小或指向缓冲区结尾的指针,4 $字节用于 size_t char *

  4. 标准分配器(空的普通类型)不需要空间,这要归功于一些实现技巧(Empty-baseclass-optimization,和也许是部分模板特化)。

  1. A data-pointer, 4 bytes for a char*.
  2. An element count or an end pointer, 4 bytes for a size_t or char*.
  3. A buffer-size or pointer to end-of-buffer, 4 bytes for a size_t or char*.
  4. The standard allocator (empty trivial type) needs no space, thanks to some implementation-tricks (Empty-baseclass-optimization, and perhaps partial template-specialization).

理论上,如果不是指针,2和3可能会更小。虽然这会很奇怪,因为它会限制最大尺寸。

In theory, 2 and 3 might be smaller if not pointers. Though that would be curious, as it would restrict the maximum size.

正如预期的那样共12个字节。

Together 12 bytes, as expected.

这篇关于空矢量的大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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