首页 > 解决方案 > std::set(rb-tree) 和 std::unordered_set(hashtable) 占用多少堆栈内存?

问题描述

考虑到比较器、哈希器和分配器是无状态的,rbtreeand的结构hashtable应该是:

template</*...*/>
struct RBTree {
    Node* header;
    size_t count;
    
    [[no_unique_address]] KeyComparer keyComparer;
    [[no_unique_address]] KeyExtracter keyOf;
    [[no_unique_address]] NodeAllocator nodeAlloc;
};

template</*...*/>
struct HashTable {
    size_t* buckets;
    Node* items;

    size_t capacity;
    size_t count;
    size_t usedBucketCount;

    [[no_unique_address]] KeyHasher keyHasher;
    [[no_unique_address]] KeyExtracter keyOf;
    [[no_unique_address]] NodeAllocator nodeAlloc;
};


static_assert(sizeof(RBTree</*...*/>) == 16);
static_assert(sizeof(HashTable</*...*/> == 40));

但实际上:

constexpr auto sizeOf_set = sizeof(std::set<double>);
// MSVC (std:c++ latest) Debug: 24
// MSVC (std:c++ latest) Release: 16
// clang 10.0.0 (-std=c++20) -O0, -O3: 48

constexpr auto sizeOf_unorderedSet = sizeof(std::unordered_set<double>);
// MSVC (std:c++ latest) Debug: 80
// MSVC (std:c++ latest) Release: 64
// clang 10.0.0 (-std=c++20) -O0, -O3: 56

对于rbtree,MSVC(发布)的结果符合我的期望。(但为什么 48 代表铿锵???)对于hashtable,我完全糊涂了......

我想知道我是否错过了一些必要的东西......

标签: c++data-structureshashtablered-black-treestack-memory

解决方案


推荐阅读