我有一个分配器感知容器,如果它是有状态的分配器(例如多态分配器),则必须存储分配器。否则,分配器不应占用任何空间。我认为 stdlib 会为此使用类似空基优化的东西,但是,我似乎无法让它工作:
#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;
};
关于c++ - 如何在容器中存储(空)分配器而不占用大小?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76570587/