本文介绍了为什么 shared_ptr 类型没有模板分配器参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

shared_ptr 定义为

shared_ptr is defined as

template< class T > class shared_ptr;

自定义分配器作为构造函数参数传递

the custom allocator is passed as constructor argument

template< class Y, class Deleter, class Alloc >
shared_ptr( Y* ptr, Deleter d, Alloc alloc );

为什么没有

template< class T, class Alloc = std::allocator<T> > class shared_ptr;

?

我觉得这在某些情况下会让生活更轻松,但另一方面它会阻止执行以下操作:

I have the feeling that this make life easier in certain cases, but on the other end it prevents doing something like:

namespace App{
    template <typename T>
    using Shared = std::shared_ptr<T,myAllocator<T>>; //pool allocator for control blocks
}

另外 make_shared 也不允许这样做,因为它已经将构造函数的参数作为参数.

Also make_shared does not allows that because it already takes as arguments the constructor's arguments.

有什么想法吗?

推荐答案

它不会让生活更轻松,因为它会人为地将 shared_ptr 的任何客户端限制为绑定到一种特定的分配器类型或通过在分配器类型上模板化自身.

It wouldn't make life easier as it would artifically constrict any client of shared_ptr to either be tied to one particular allocator type or itself by templated on an allocator type.

只有一些构造函数和函数(例如一些 reset 重载)需要知道用于分配共享对象的分配器.许多客户端可以愉快地与分配器无关.

Only some constructors and functions (e.g. some reset overloads) need to know about the allocator used to allocated the shared object. Many clients can happily be allocator agnostic.

在类型上使用更少的模板参数是更少约束.请注意,类类型的模板参数通常必须明确指定,而在函数模板上,它们通常可以从参数中推导出来.

Having fewer template parameters on the type is less constraining. Note that template parameters on class types must usually be specified explicitly where as on function templates they can often be deduced from parameters.

这篇关于为什么 shared_ptr 类型没有模板分配器参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-01 12:52