c++ - 弃用 std::allocator
问题描述
相关:为什么标准容器要求 allocator_type::value_type 是元素类型?
据说自 C++17 以来已弃用以下内容:
template<>
struct allocator<void>;
我想知道它是否已被弃用,因为现在仅主模板本身就能够容纳allocator<void>
,还是allocator<void>
不推荐使用 of 的用例。
如果是后者,我想知道为什么。我认为allocator<void>
在指定不绑定到特定类型的分配器时很有用(所以只是一些模式/元数据)。
解决方案
这不是std::allocator<void>
被弃用的,只是它不是一个明确的专业化。
它过去的样子是这样的:
template<class T>
struct allocator {
typedef T value_type;
typedef T* pointer;
typedef const T* const_pointer;
// These would be an error if T is void, as you can't have a void reference
typedef T& reference;
typedef const T& const_reference;
template<class U>
struct rebind {
typedef allocator<U> other;
}
// Along with other stuff, like size_type, difference_type, allocate, deallocate, etc.
}
template<>
struct allocator<void> {
typedef void value_type;
typedef void* pointer;
typedef const void* const_pointer;
template<class U>
struct rebind {
typdef allocator<U> other;
}
// That's it. Nothing else.
// No error for having a void&, since there is no void&.
}
现在,由于std::allocator<T>::reference
和std::allocator<T>::const_reference
已被弃用,因此不需要为void
. 您可以使用std::allocator<void>
,以及std::allocator_traits<std::allocator<void>>::template rebind<U>
获取std::allocator<U>
,但不能实例化std::allocator<void>::allocates
。
例如:
template<class Alloc = std::allocator<void>>
class my_class; // allowed
int main() {
using void_allocator = std::allocator<void>;
using void_allocator_traits = std::allocator_traits<void_allocator>;
using char_allocator = void_allocator_traits::template rebind_alloc<char>;
static_assert(std::is_same<char_allocator, std::allocator<char>>::value, "Always works");
// This is allowed
void_allocator alloc;
// These are not. Taking the address of the function or calling it
// implicitly instantiates it, which means that sizeof(void) has
// to be evaluated, which is undefined.
void* (void_allocator::* allocate_mfun)(std::size_t) = &void_allocator::allocate;
void_allocator_traits::allocate(alloc, 1); // calls:
alloc.allocate(1);
}
推荐阅读
- c++ - boost::serialization 如何与 C++ 中的 std::unique_ptr 一起使用
- c# - 带有多个斜杠的 RestfulAPI URL 正常响应
- sql - 编写多案例语句 SQL 的更好方法
- c - 使用 scanf 读取大字符串时的 SegFault/Abort
- c# - .NET Core 2.2 中的自定义 JWT 令牌验证
- go - 模块声明为 X 但要求为 Y
- codeigniter - 将所见即所得与 codeigniter 结合起来
- php - 使用 Slim 框架创建 Rest Api 的 index.php 文件出错
- javascript - 如何用 HOC 包装每个导出的组件?
- python - 在 Python 中导入继承的类