Boost shared_ptr:如何使用自定义删除器和分配器
自由函数allocate_shared可以与任何符合标准的分配器一起使用。但是shared_ptr的构造函数和reset方法呢?
template<class Y, class D, class A> shared_ptr(Y * p, D d, A a);
template<class Y, class D, class A> void reset(Y * p, D d, A a);
手册中说,D应该提供一个调用运算符,用于删除指针,并且A必须是一个符合标准的分配器。如果是这样,为什么需要D? A 不能同时进行分配和解除分配吗? 您不认为为每个自定义分配器提供删除器的要求使得上述方法几乎毫无用处吗?当我使用自定义分配器时,我会选择allocate_shared。我如何知道释放自定义分配器分配的内存的正确方法是什么?
编辑:经过对逐字分配器和删除器的一些实验,我发现分配器传递给shared_ptr的构造函数和工厂函数allocate_shared > 仅用于分配shared_ptr的内部结构。 allocate_shared 从不使用传递的分配器来分配共享对象。我认为 boost 手册可以更明确地解释如何使用分配器。
Free function allocate_shared can be used with any standard compliant allocator. But what about shared_ptr's constructor and reset method.
template<class Y, class D, class A> shared_ptr(Y * p, D d, A a);
template<class Y, class D, class A> void reset(Y * p, D d, A a);
The manual says that D should provide a call operator which will be used to delete the pointer and A must be a standard compliant allocator. If so, why D is needed? Can't A do both allocation and delocation? Don't you think that the requirement to provide a deleter for every custom allocator makes the above methods pretty much useless? When I use custom allocators, I go for allocate_shared. How do I know what is the proper way to free memory allocated by a custom allocator?
EDIT: After some experimentation with a verbatim allocator and a deleter I figured out that the allocator passed to the constructor of shared_ptr and to the factory function allocate_shared is used to allocate the internal structure of shared_ptr only. allocate_shared never uses the passed allocator to allocate the shared object. I think that the boost manual could have explained how the allocator is used more explicitly.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
分配器旨在用于分配和释放内部
shared_ptr
详细信息,而不是对象。也就是说,虽然删除器使我们能够完全控制共享对象(因为我们控制它的获取和释放方式),但分配器参数使我们能够控制对象共享性质的内部细节。
如果您查看N2351,在分配器提案的末尾,他们指出 Boost 已经实现了该功能,并链接到一个演示其用途的示例。
这是逐字的例子:
The allocator is intended to be used to allocate and deallocate internal
shared_ptr
details, not the object.That is, while the deleter gives us full control over our shared object (because we control how it's acquired and released), the allocator parameter gives us control over the internal details of our object's shared nature.
If you look at N2351, at the end of the allocator proposal they note that Boost has implemented the feature, and link to an example that was made to demonstrate its use.
Here is that example, verbatim: