来自cppreference中的std::allocate_shared:
使用
args
作为T
构造函数的参数列表,构造一个T
类型的对象,并将其包装在std::shared_ptr
中。该对象的构造方式类似于表达式::new (pv) T(std::forward<Args>(args)...)
,其中pv
是一个内部的void*
指针,用于存储适合容纳T
类型对象的内存。该存储通常比sizeof(T)
大,以便为共享指针的控制块和T
对象使用一个分配。所有内存分配都使用
alloc
的副本完成,alloc
必须满足Allocator
的要求。
我感到困惑的是,考虑下面的用户定义的分配器,同样来自cppreference
template <class T>
struct Mallocator {
typedef T value_type;
Mallocator() = default;
template <class U> Mallocator(const Mallocator<U>&) {}
T* allocate(std::size_t n) { return static_cast<T*>(std::malloc(n * sizeof(T))); }
void deallocate(T* p, std::size_t) { std::free(p); }
};
template <class T, class U>
bool operator==(const Mallocator<T>&, const Mallocator<U>&) { return true; }
template <class T, class U>
bool operator!=(const Mallocator<T>&, const Mallocator<U>&) { return false; }
由于Mallocator
只能分配sizeof(T)
大小的内存,那么allocate_shared
如何分配比sizeof(T)
更大的存储空间,以便将一个分配用于共享指针的控制块和T
对象?