- memory_resource[meta header]
- function[meta id-type]
- std::pmr[meta namespace]
- polymorphic_allocator[meta class]
- cpp17[meta cpp]
Tp* allocate(std::size_t n); // (1) C++17
[[nodiscard]] Tp* allocate(std::size_t n); // (1) C++20
Tp* allocate(std::size_t n); // (1) C++26
指定された分のメモリ領域を確保する
n
-- 確保する領域の数、バイト数ではなく配列の要素数相当
利用するmemory_resource
のポインタをmemory_rsrc
というメンバに保持しているとすると、以下と等価である。
return static_cast<Tp*>(memory_rsrc->allocate(n * sizeof(Tp), alignof(Tp)));
確保した領域の先頭へのポインタ。
SIZE_MAX
/ sizeof(Tp) < n
である場合、std::length_error
例外を送出する- 指定されたサイズの領域が確保できない場合は、任意の例外を送出する
#include <iostream>
#include <memory_resource>
int main()
{
std::pmr::polymorphic_allocator<int> alloc{};
//メモリの確保
int* array = alloc.allocate(4);
//要素を構築
for (int i = 0; i < 4; ++i) {
alloc.construct(array + i, i);
}
for (int i = 0; i < 4; ++i) {
std::cout << array[i] << std::endl;
}
//要素を破棄
for (int i = 0; i < 4; ++i) {
alloc.destroy(array + i);
}
//メモリの解放
alloc.deallocate(array, 4);
}
- allocate[color ff0000]
- construct[link construct.md]
- destroy[link destroy.md]
- deallocate[link deallocate.md]
0
1
2
3
- C++17
- Clang: ??
- GCC: 9.1 [mark verified]
- Visual C++: 2017 update 6 [mark verified]
- P0220R1 Adopt Library Fundamentals V1 TS Components for C++17 (R1)
- P0337r0 | Delete operator= for polymorphic_allocator
- Working Draft, C++ Extensions for Library Fundamentals, Version 2
- P0600R1
[[nodiscard]]
in the Library, Rev1- C++20で
constexpr
が付加された
- C++20で
- LWG Issue 3038.
polymorphic_allocator::allocate
should not allow integer overflow to create vulnerabilities - P2422R1 Remove
nodiscard
annotations from the standard library specification- C++26で
[[nodiscard]]
指定が削除された
- C++26で