allocator_traits::deallocate 是有效的 shared_ptr 删除器
is allocator_traits::deallocate a valid shared_ptr deleter
我想这个问题实际上是关于 std::allocator_traits
的设计和提供自定义分配器的。如果我想使用自定义分配器构造一个 std::shared_ptr<>
,我可以使用 std::allocator_traits 吗?
基本上,这是正确的吗?
WidgetAllocator allocator;
std::shared_ptr<Widget> widget(allocator.allocate(), std::allocator_traits<WidgetAllocator>::deallocate);
Basically, is this correct?
std::shared_ptr<Widget> widget(allocator.allocate(), std::allocator_traits<WidgetAllocator>::deallocate);
这是不正确的。
首先,不保证分配器具有无效 allocate
成员函数。
好的,让我们假设 WidgetAllocator
确实提供了这样的重载,尽管这对于分配器来说并不是很典型。但更重要的是,std::allocator_traits::deallocate
不能用 Widget*
调用。它的参数列表是 ( Alloc& a, pointer p, size_type n )
.
So what's the recommended use of allocator_traits?
只要你想使用分配器的可选功能之一,你就应该使用std::allocator_traits
,比如Alloc::is_always_equal
,以及你想要的分配器使用不提供可选功能,或者分配器是模板参数,并且您希望支持所有分配器,无论它们是否提供可选功能。
std::allocator_traits
为分配器的可选功能提供默认实现。
Should I be invoking methods on the allocator directly?
您可以直接调用成员函数,如果您使用的分配器提供了它们,或者在一般情况下,如果它们是非可选的。不过,直接调用成员不是必需的,您始终可以使用分配器特征。
我想这个问题实际上是关于 std::allocator_traits
的设计和提供自定义分配器的。如果我想使用自定义分配器构造一个 std::shared_ptr<>
,我可以使用 std::allocator_traits 吗?
基本上,这是正确的吗?
WidgetAllocator allocator;
std::shared_ptr<Widget> widget(allocator.allocate(), std::allocator_traits<WidgetAllocator>::deallocate);
Basically, is this correct?
std::shared_ptr<Widget> widget(allocator.allocate(), std::allocator_traits<WidgetAllocator>::deallocate);
这是不正确的。
首先,不保证分配器具有无效 allocate
成员函数。
好的,让我们假设 WidgetAllocator
确实提供了这样的重载,尽管这对于分配器来说并不是很典型。但更重要的是,std::allocator_traits::deallocate
不能用 Widget*
调用。它的参数列表是 ( Alloc& a, pointer p, size_type n )
.
So what's the recommended use of allocator_traits?
只要你想使用分配器的可选功能之一,你就应该使用std::allocator_traits
,比如Alloc::is_always_equal
,以及你想要的分配器使用不提供可选功能,或者分配器是模板参数,并且您希望支持所有分配器,无论它们是否提供可选功能。
std::allocator_traits
为分配器的可选功能提供默认实现。
Should I be invoking methods on the allocator directly?
您可以直接调用成员函数,如果您使用的分配器提供了它们,或者在一般情况下,如果它们是非可选的。不过,直接调用成员不是必需的,您始终可以使用分配器特征。