如何将Deleter传递给make_shared? [英] How to pass deleter to make_shared?
问题描述
从C ++ 11开始,由于多种原因,开发人员倾向于将智能指针类用于动态生命周期对象。对于这些新的智能指针类,标准甚至建议不要使用 new
这样的运算符,而是建议使用 make_shared
或 make_unique
可以避免某些错误。
Since C++11, because of several reasons, developers tend to use smart pointer classes for dynamic lifetime objects. And with those new smart pointer classes, standards, even suggest to not use operators like new
instead they suggest to use make_shared
or make_unique
to avoid some error prone.
如果我们想使用智能指针类,例如 shared_ptr
,我们可以构造一个类似的
If we like to use a smart pointer class, like shared_ptr
, we can construct one like,
shared_ptr<int> p(new int(12));
我们还要将自定义删除器传递给智能指针类,
Also we would like to pass a custom deleter to smart pointer classes,
shared_ptr<int> p(new int(12), deleter);
另一方面,如果我们想使用 make_shared
进行分配,例如。 int
,而不是使用 new
和 shared_ptr
构造函数,例如在上面的第一个表达式中,我们可以使用
On the other hand, if we like to use make_shared
to allocate, for ex. int
, instead of use new
and shared_ptr
constructor, like on the first expression above, we can use
auto ip = make_shared<int>(12);
但是如果我们还希望将自定义删除器传递给 make_shared
,有正确的方法吗?好像编译器,至少是gcc,会出错,
But what if we like to also pass a custom deleter to make_shared
, is there a right way to do that? Seems like compilers, at least gcc, gives an error to,
auto ip = make_shared<int>(12, deleter);
推荐答案
正如其他人所说, make_shared
不能与自定义删除器一起使用。但是我想解释为什么。
As other have said, make_shared
cannot be used with a custom deleter. But I want to explain why.
存在自定义删除器是因为您以某种特殊方式分配了指针,因此您需要能够以相应的特殊方式对其进行分配。好吧, make_shared
用 new
分配指针。分配了 new
的对象应通过 delete
释放。
Custom deleters exist because you allocated the pointer in some special way, and therefore you need to be able to deallocate it in a correspondingly special way. Well, make_shared
allocates the pointer with new
. Objects allocated with new
should be deallocated with delete
. Which the standard deleter dutifully does.
简而言之,如果您可以使用默认的分配行为,则可以使用默认的 deallocation 行为。太。而且,如果您不能采用默认的分配行为,则应使用 allocate_shared
,它使用提供的分配器来分配和取消分配存储。
In short, if you can live with the default allocation behavior, you can live with the default deallocation behavior too. And if you can't live with the default allocation behavior, you should use allocate_shared
, which uses the provided allocator to both allocate and deallocate the storage.
此外, make_shared
被允许(并且几乎肯定会)在同一分配中分配 T
的内存和shared_ptr的控制块。这是您的删除者无法真正了解或处理的事情。 allocate_shared
可以处理它,因为您提供的分配器可以执行分配和释放任务。
Also, make_shared
is allowed to (and almost certainly will) allocate the memory for T
and the control block for the shared_ptr within the same allocation. This is something that your deleter can't really know about or deal with. Whereas allocate_shared
is capable of handling it, since the allocator you provide can do allocation and deallocation duties.
这篇关于如何将Deleter传递给make_shared?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!