C++ STL:为什么分配器不增加容器的内存占用?



下面的代码片段(参见godbolt)显示大的分配器不会增加STL容器的内存占用,但是大的比较器会。为什么会这样呢?

// compiled with x86-64 gcc 10.3, -std=c++17
#include <functional>
#include <iostream>
#include <memory>
#include <set>
struct MyLess : public std::less<int>
{
char dummy[1024];
};
struct MyAllocator : public std::allocator<int>
{
char dummy[1024];
};
int main()
{
std::cout << sizeof(std::set<int, MyLess>) << std::endl;  // prints 1064
std::cout << sizeof(std::set<int, std::less<int>, MyAllocator>) << std::endl;  // prints 48
return 0;
}

您的分配器未被使用。

默认情况下,std::set接收std::allocator<int>,但需要分配某种节点,而不是ints。它使用std::allocator_traits::rebind为其内部节点类型获取不同的分配器。

pre - c++ 20std::allocator有一个rebind成员类型,你继承它,std::allocator_traits::rebind找到它。rebind指向std::allocator,这就是你得到的。

从c++ 20开始,在std::allocator中没有rebind,因此std::allocator_traits::rebind退回到直接修改分配器的第一个模板参数,并且由于它不是模板,因此您会得到编译错误。

一个可能的解决方案是使您的分配器成为一个模板,并提供您自己的rebind(它可以是畸形的,然后模板参数将被自动替换):

template <typename T>
struct MyAllocator : public std::allocator<T>
{
char dummy[1024];
struct rebind {}; // Malformed `rebind` to hide the inherited one, if any.
};

然后为我打印1072

最新更新