这样使用 rebind_alloc 是错误的吗?
Is this use of rebind_alloc an error?
在boost.asio的一个官方例子中,我找到了如下代码:
template <class Func, class Alloc>
void post(Func f, const Alloc& a) const
{
auto p(std::allocate_shared<item<Func>>(
typename std::allocator_traits<
Alloc>::template rebind_alloc<char>(a),
priority_, std::move(f)));
std::lock_guard<std::mutex> lock(context_.mutex_);
context_.queue_.push(p);
context_.condition_.notify_one();
}
是否应该将rebind_alloc<char>
修改为rebind_alloc<item<Func>>
?
没关系。 allocate_shared
的规范说:
The allocate_shared
templates use a copy of a
(rebound for an unspecified value_type
) to allocate memory.
该函数从不直接分配指针对象;它通常会分配一个 shared_ptr 带有嵌入式指针的控制块。因此,您通过的任何分配都必须重新启动。
重新绑定到 char
的优点是它更短,并且不必针对所使用的类型进行调整。 (int
可能更短,但 char
有时被理解为 "raw memory"。)重新绑定到 pointee 类型的优点是它不会对其他程序员造成混淆。
在boost.asio的一个官方例子中,我找到了如下代码:
template <class Func, class Alloc>
void post(Func f, const Alloc& a) const
{
auto p(std::allocate_shared<item<Func>>(
typename std::allocator_traits<
Alloc>::template rebind_alloc<char>(a),
priority_, std::move(f)));
std::lock_guard<std::mutex> lock(context_.mutex_);
context_.queue_.push(p);
context_.condition_.notify_one();
}
是否应该将rebind_alloc<char>
修改为rebind_alloc<item<Func>>
?
没关系。 allocate_shared
的规范说:
The
allocate_shared
templates use a copy ofa
(rebound for an unspecifiedvalue_type
) to allocate memory.
该函数从不直接分配指针对象;它通常会分配一个 shared_ptr 带有嵌入式指针的控制块。因此,您通过的任何分配都必须重新启动。
重新绑定到 char
的优点是它更短,并且不必针对所使用的类型进行调整。 (int
可能更短,但 char
有时被理解为 "raw memory"。)重新绑定到 pointee 类型的优点是它不会对其他程序员造成混淆。