gpt4 book ai didi

c++ - 为什么 libc++ 的 std::string 实现占用 3 倍于 libstdc++ 的内存?

转载 作者:IT老高 更新时间:2023-10-28 22:15:40 24 4
gpt4 key购买 nike

考虑以下测试程序:

#include <iostream>
#include <string>
#include <vector>

int main()
{
std::cout << sizeof(std::string("hi")) << " ";
std::string a[10];
std::cout << sizeof(a) << " ";
std::vector<std::string> v(10);
std::cout << sizeof(v) + sizeof(std::string) * v.capacity() << "\n";
}

libstdc++libc++ 的输出分别为:

8 80 104
24 240 264

如您所见,libc++ 占用的内存是简单程序的 3 倍。导致这种内存差异的实现有何不同?我需要担心吗?如何解决?

最佳答案

这是一个简短的程序,可帮助您探索 std::string 的两种内存使用情况:堆栈和堆。

#include <string>
#include <new>
#include <cstdio>
#include <cstdlib>

std::size_t allocated = 0;

void* operator new (size_t sz)
{
void* p = std::malloc(sz);
allocated += sz;
return p;
}

void operator delete(void* p) noexcept
{
return std::free(p);
}

int
main()
{
allocated = 0;
std::string s("hi");
std::printf("stack space = %zu, heap space = %zu, capacity = %zu\n",
sizeof(s), allocated, s.capacity());
}

使用 http://melpon.org/wandbox/很容易获得不同编译器/库组合的输出,例如:

gcc 4.9.1:

stack space = 8, heap space = 27, capacity = 2

gcc 5.0.0:

stack space = 32, heap space = 0, capacity = 15

clang/libc++:

stack space = 24, heap space = 0, capacity = 22

VS-2015:

stack space = 32, heap space = 0, capacity = 15

(最后一行来自http://webcompiler.cloudapp.net)

上面的输出还显示了 capacity,它衡量了字符串在必须从堆中分配一个新的、更大的缓冲区之前可以容纳多少个 char .对于 gcc-5.0、libc++ 和 VS-2015 实现,这是 短字符串缓冲区 的度量。即在栈上分配大小缓冲区来保存短字符串,从而避免了更昂贵的堆分配。

似乎 libc++ 实现具有最小的(堆栈使用)短字符串实现,但包含最大的短字符串缓冲区。如果计算 total 内存使用量(堆栈 + 堆),libc++ 在所有 4 种实现中对于这 2 个字符的字符串的总内存使用量最小。

需要注意的是,所有这些测量都是在 64 位平台上进行的。在 32 位上,libc++ 堆栈使用量将下降到 12,小字符串缓冲区下降到 10。我不知道 32 位平台上其他实现的行为,但您可以使用上面的代码找出.

关于c++ - 为什么 libc++ 的 std::string 实现占用 3 倍于 libstdc++ 的内存?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27631065/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com