cpp/memory/allocator/allocate:修订间差异
来自cppreference.com
无编辑摘要 |
小无编辑摘要 |
||
| (未显示3个用户的16个中间版本) | |||
| 第2行: | 第2行: | ||
{{cpp/memory/allocator/navbar}} | {{cpp/memory/allocator/navbar}} | ||
{{dcl begin}} | {{dcl begin}} | ||
{{dcl | num=1 | until=c++17 | 1= | {{dcl |num=1 | ||
pointer allocate( size_type n, | |until=c++17|1= | ||
pointer allocate( size_type n, voidhint = 0 ); | |||
}} | }} | ||
{{dcl | {{dcl|since=c++17|=|1= | ||
T* allocate( std::size_t n, const void * hint); | T* allocate( std::size_t n, const void* hint ); | ||
}} | }} | ||
{{dcl | num=2 | | {{dcl | ||
|num=2|=c++17|= | |||
T* allocate( std::size_t n ); | T* allocate( std::size_t n ); | ||
}} | }} | ||
{{dcl end}} | {{dcl end}} | ||
调用 {{c|::operator new(std::size_t)}} 分配 {{c|n * sizeof(T)}} 字节的未初始化存储,但何时及如何调用此函数是未指定的。指针 {{|hint}} 可用于提供引用的局部性:实现支持,allocator 会试图分配尽可能接近 {{|hint}} 的新内存块。 | |||
===参数=== | ===参数=== | ||
{{par begin}} | {{par begin}} | ||
{{par | n | | {{par|n|要分配存储的对象数}} | ||
{{par | hint | | {{par|hint|指向临近内存位置的指针}} | ||
{{par end}} | {{par end}} | ||
===返回值=== | ===返回值=== | ||
指向 | 指向 {{tt|T}} 类型的 {{|n}} 个对象数组首的指针。 | ||
===异常=== | ===异常=== | ||
分配失败抛出 {{lc|std::bad_alloc}} | |||
。 | |||
=== | ====== | ||
|或{{tt|}} | |||
++:: | |||
===参阅=== | ===参阅=== | ||
{{dsc begin}} | {{dsc begin}} | ||
{{dsc inc | cpp/memory/allocator_traits/dsc allocate}} | {{dsc inc|cpp/memory/allocator_traits/dsc allocate}} | ||
{{dsc end}} | {{dsc end}} | ||
{{langlinks|de|en|es|fr|it|ja|pt|ru}} | {{langlinks|de|en|es|fr|it|ja|pt|ru}} | ||
2024年7月1日 (一) 10:04的最新版本
| (1) | ||
| |
(C++17 前) | |
| |
(C++17 起) (弃用) (C++20 移除) |
|
| (2) | (C++17 起) (C++20 前) |
|
| (C++20 起) | ||
调用 ::operator new(std::size_t) 或 ::operator new(std::size_t, std::align_val_t) (C++17 起)分配 n * sizeof(T) 字节的未初始化存储,但何时及如何调用此函数是未指定的。指针 hint 可用于提供引用的局部性:如果实现支持,那么 allocator 会试图分配尽可能接近 hint 的新内存块。
然后,此函数在该存储中创建一个 T[n] 数组并开始其生存期,但不开始其任何元素的生存期。
如果 T 是不完整类型,那么此函数的使用非良构。
|
为了在常量表达式中使用此函数,必须在同一表达式的求值内解分配它分配的存储。 |
(C++20 起) |
参数
| n | - | 要分配存储的对象数 |
| hint | - | 指向临近内存位置的指针 |
返回值
指向 T 类型的 n 个对象的数组首元素的指针,数组元素尚未构造。
异常
|
如果 |
(C++11 起) |
如果分配失败,那么就会抛出 std::bad_alloc。
注解
遣词“未指定何时及如何”令标准库容器可以组合或优化掉堆分配,即使对直接调用 ::operator new 禁止这种优化。例如 libc++ 实现了它([1] 与 [2])
在调用 allocate() 后、构造元素前,T* 的指针算术在分配的数组内是良定义的,但如果访问元素那么行为未定义。
缺陷报告
下列更改行为的缺陷报告追溯地应用于以前出版的 C++ 标准。
| 缺陷报告 | 应用于 | 出版时的行为 | 正确行为 |
|---|---|---|---|
| LWG 578 | C++98 | hint 必须是 0 或者先前从 allocate()返回但还没有传递给 deallocate() 的指针 |
移除该要求 |
| LWG 3190 | C++11 | allocate() 可能分配大小错误的存储
|
改成抛出 std::bad_array_new_length |
参阅
[静态] |
用分配器分配未初始化的存储 ( std::allocator_traits<Alloc> 的公开静态成员函数)
|