弃用标准::分配器<void>
Deprecation of std::allocator<void>
相关:为什么标准容器需要allocator_type::value_type作为元素类型?
据说以下内容自 C++17 起已被弃用:
template<>
struct allocator<void>;
我想知道它是否被弃用,因为现在仅主模板就能够容纳allocator<void>
,或者allocator<void>
的用例已被弃用。
如果是后者,我想知道为什么。我认为allocator<void>
指定未绑定到特定类型的分配器(因此只是一些架构/元数据(很有用。
根据 p0174r0
类似地,定义
std::allocator<void>
以便各种模板 重新绑定技巧可以在原始的 C++98 库中工作,但它是 不是实际的分配器,因为它既缺乏allocate
又缺乏deallocate
成员函数,默认情况下无法从allocator_traits
.这种需求随着C++11和void_pointer
而消失了 并在allocator_traits中const_void_pointer
键入别名。但是,我们 继续指定它以避免破坏具有 尚未升级以支持通用分配器,根据 C++11。
并不是说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);
}
- 为什么随机数生成器不在void函数中随机化数字,而在main函数中随机化
- 在c++类上调用void函数
- 为什么野牛仍在使用"int yylex(void)",却找不到"int yylex(YYS
- 在派生函数中指定void*参数
- C++为什么尽管我调用了void函数,它却不起作用
- 如何从void函数输出字符串
- 我应该使用什么来代替void作为变体中的替代类型之一
- 奇怪的结构&GCC&clang(void*返回类型)
- Arduino:for/while/if在void setup()或void loop()之前?——错误:之前需要不合格
- 为什么这个函数将"const char*"转换为"void* const"而不是"const void*"
- 引用一个已擦除类型(void*)的指针
- 将尾部调用void(i32,..)位转换为llvm::函数以获取FnAttribute
- 库函数需要一个 std::function<void(void)>,如何传入类函数?
- 如何将指针从一个void函数传递到另一个C++
- 为什么我在使用void函数时得到错误代码C2276
- EASTL矢量<向量<int>>连续的
- void*到驱动程序中的UnicodeString
- 为什么在逗号分隔符上下文中将预增量的结果强制转换为void
- 指针没有更新它在void函数内部指向的值
- 不能将 "void *" 类型的值分配给类型 "TCHAR" 的实体