• Class / Function / Type

      std::
    • Header file

      <>
    • Other / All

    最終更新日時(UTC):
    が更新

    履歴 編集

    function
    <memory_resource>

    std::pmr::polymorphic_allocator::allocate_object

    template <class T>
    [[nodiscard]] T* allocate_object(size_t n = 1); // (1) C++20
    template <class T>
    T* allocate_object(size_t n = 1);               // (1) C++26
    

    概要

    指定された個数のT型の配列として十分なメモリを確保する。

    引数

    • n -- 確保する領域の数、バイト数ではなく配列の要素数相当

    効果

    以下と等価。

    return static_cast<T*>(this->allocate_bytes(n*sizeof(T), alignof(T)));
    

    戻り値

    確保した領域の先頭へのポインタ。

    例外

    SIZE_MAX / sizeof(T) < nである場合、std::length_error例外を送出する

    備考

    Tは引数から推論することができないため、明示的に指定する必要がある。

    #include <iostream>
    #include <memory_resource>
    
    int main() {
    
      constexpr int N = 10;
    
      std::pmr::polymorphic_allocator<> alloc{};
    
      //int型10個分の領域を確保
      int* p = alloc.allocate_object<int>(N);
    
      //確保した領域にintのオブジェクトを構築
      for (int i = 0; i < N; ++i) {
        alloc.construct(p+i, i);
      }
    
    
      for (int i = 0; i < N; ++i) {
        std::cout << p[i] << "\n";
      }
    
    
      //領域上のオブジェクトを破棄
      for (int i = 0; i < N; ++i) {
        alloc.destroy(p+i);
      }
    
      //確保したメモリ領域を解放
      alloc.deallocate_object(p, N);
    }
    

    出力

    0
    1
    2
    3
    4
    5
    6
    7
    8
    9
    

    バージョン

    言語

    • C++20

    処理系

    関連項目

    参照