Skip to content

Latest commit

 

History

History
98 lines (79 loc) · 3 KB

File metadata and controls

98 lines (79 loc) · 3 KB

allocate

  • 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

処理系

関連項目

参照