allocator_traits :: construct()vs allocator_traits :: allocate() [英] allocator_traits::construct() vs allocator_traits::allocate()
问题描述
C ++ 11提供 std :: allocator_traits
类作为使用分配器的标准方法。静态函数 std :: allocator_traits :: construct()
采用一个指针来构建对象。然而, std :: allocator_traits :: allocate()
静态函数返回一个 allocator :: pointer
只需要表现得像一个指针,但它不一定是一个(一般来说, std :: allocator :: pointer
需要一个指针)。
C++11 provides the std::allocator_traits
class as the standard way to use allocators. The static function std::allocator_traits::construct()
takes a pointer to where the object should be constructed. The std::allocator_traits::allocate()
static function, however, returns an allocator::pointer
value, which only has to behave like a pointer but it is not necessarily one (in general, although std::allocator::pointer
is required to be a pointer).
如果一般来说,它们将使用不兼容的类型,那么如何使用分配和构造静态方法?只有当指针
类型实际上可以转换为普通普通指针时,它们才可以使用?
How is one supposed to use the allocation and construction static methods if, in general, they will work with incompatible types? Can they be used only if the pointer
type is actually convertible to a normal plain pointer?
推荐答案
有两种方法可以根据你现在的情况做。
There are two techniques to do this depending on what you have at the moment.
如果你有一个左值表达式,节点,那么你可以使用std :: addressof这样:
If you have an lvalue expression, say the value field in a node, then you can use std::addressof like so:
allocator_traits<allocator_type>::construct(alloc, std::addressof(ptr->value), ...);
其中 ptr
是 allocator_type :: pointer
。
但是,如果你没有一个字段要取消引用, c> allocator_type :: pointer 到 T *
,你需要先实现一个技巧:
However if you don't have a field to dereference and you want to convert an allocator_type::pointer
to T*
, there's a trick you need to implement first:
template <class T>
inline
T*
to_raw_pointer(T* p) noexcept
{
return p;
}
template <class Pointer>
inline
typename std::pointer_traits<Pointer>::element_type*
to_raw_pointer(Pointer p) noexcept
{
return p != nullptr ? ::to_raw_pointer(p.operator->())
: nullptr;
}
现在您可以说:
allocator_traits<allocator_type>::construct(alloc, to_raw_pointer(ptr), ...);
这篇关于allocator_traits :: construct()vs allocator_traits :: allocate()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!