首页 > 解决方案 > 为什么我们需要 allocate_shared 而不是向 make_shared 添加传递自定义分配器的能力?

问题描述

我知道 shared_ptr 具有allocate_shared以下函数签名(例如,有更多重载):

template< class T, class Alloc, class... Args >
shared_ptr<T> allocate_shared( const Alloc& alloc, Args&&... args );

...这使我们可以使用自己的分配器实现来构建动态创建的对象 a shared_ptr

std::shared_ptr<int> ptr = std::allocate_shared<int>(std::allocator<int>(), 2);

与具有模板分配器类型的 stl 容器相比,我发现这种语法奇怪且不直观:

std::vector<T, Alloc=std::allocator<T>>

我不确定是否可以将默认模板参数class Alloc与可变参数模板结合使用,因此,如果确实是委员会将自己逼入绝境并且这是他们唯一的选择,那么我愿意接受一个答案。但是,假设情况并非如此 - 为什么标准委员会不选择如下语法:

shared_ptr<int> ptr = std::make_shared<int, std::allocator<int>>(std::allocator<int>(), 2)

甚至

shared_ptr<int, std::allocator<T>> ptr = std::make_shared<int>(2)

(分配器参数可以默认为向后兼容)而是为它创建一个全新的函数?

标签: c++c++11memory-managementshared-ptrallocation

解决方案


推荐阅读