c++ - 如何在容器中存储(空)分配器而不占用大小?

标签 c++ allocator

我有一个分配器感知容器,如果它是有状态的分配器(例如多态分配器),则必须存储分配器。否则,分配器不应占用任何空间。我认为 stdlib 会为此使用类似空基优化的东西,但是,我似乎无法让它工作:

Demo

#include <cstdio>
#include <memory>
#include <memory_resource>
#include <iostream>


template <typename T, typename Allocator>
struct MyContainerBase {
    Allocator allocator;
};

template <typename T, typename Allocator = std::allocator<T>>
struct MyContainer : private MyContainerBase<T, Allocator>
{
    using base_ = MyContainerBase<T, Allocator>;

    T myint_;
};

int main() {
    MyContainer<int> c;

    std::cout << "size = " << sizeof(MyContainer<int>) << std::endl;
}

产量

size = 8

我查看了 vector 的 libc++ 和 libstdc++ 实现,但我根本找不到存储的分配器?但它仍然可以与 pmr 分配器一起使用。我该怎么做呢?另外,我至少必须有一些分配器对象引用与 std::allocator_traits<Allocator>(myalloc); 一起使用。

最佳答案

在 C++20 之前,这需要使用空基优化,但使用 C++20 解决方案非常简单:使用 no_unique_address attribute :

template <typename T, typename Allocator>
struct MyContainerBase {
#ifdef _MSC_VER
    [[msvc::no_unique_address]]
#else
    [[no_unique_address]]
#endif
    Allocator allocator;
};

online compiler

关于c++ - 如何在容器中存储(空)分配器而不占用大小?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76570587/

相关文章:

c++ - 访问可执行文件的全局变量时出现共享库链接器错误

c++ - 检查具有特定格式的字符数组值

c++ - std::map 是否通过引用、按值获取分配器或纯粹将其用作类型?

c++ - 几个小 std::vectors 的连续内存分配?

c++ - 强制 vector 的分配器指向特定位置

c++ - 包含字符串的结构的 Boost Interprocess vector 是否需要特殊分配器?

c++ - 为什么要两次使用静态库才能使编译工作?

c++ - 如何在不复制数据且不暴露指针的情况下向用户检索数据对象?

c++ - GetQueuedCompletionStatus 在 UDP 套接字上无限期阻塞

c++ - 我可以使用std::array的自定义分配器来获得安全的加密 key 吗?