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

履歴 編集

function template
<memory>

std::make_obj_using_allocator(C++20)

template<class T, class Alloc, class... Args>
  T make_obj_using_allocator(const Alloc& alloc, Args&&... args);

概要

Alloc 型のアロケータオブジェクト alloc、および、コンストラクタ引数 args を用いて、T 型のオブジェクトを uses-allocator 構築する。

構築対象の型 T は関数引数からは推論できないため、明示的に指定する必要がある。

戻り値

以下と同等

備考

  • uses_allocator_construction_args を見ればわかる通り、uses-allocator 構築は、その名前に反して必ずしもアロケータオブジェクトを使うとは限らないので注意。
    uses_allocator_v<T, Alloc>false の場合、アロケータオブジェクト alloc は無視される)

#include <iostream>
#include <vector>
#include <utility>
#include <memory>
#include <new>

// 状態付きアロケータ
template <typename T>
class MyAlloc {
public:
  using value_type = T;
  T* allocate(std::size_t n) { return static_cast<T*>(::operator new(sizeof(T) * n)); }
  void deallocate(T* p, std::size_t n) { ::operator delete(static_cast<void*>(p), sizeof(T) * n); }
  MyAlloc(int state) noexcept : state(state) {}
  template <typename U>
  MyAlloc(const MyAlloc<U>& o) noexcept : state(o.state) {}
  int state;
};

template <typename T>
bool operator==(const MyAlloc<T>& lhs, const MyAlloc<T>& rhs) noexcept
{
  return lhs.state == rhs.state;
}

template <typename T>
bool operator!=(const MyAlloc<T>& lhs, const MyAlloc<T>& rhs) noexcept
{
  return lhs.state != rhs.state;
}

// 型別名
using VEC = std::vector<int, MyAlloc<int>>;

using V = std::pair<std::pair<VEC, int>, int>;

int main()
{
  auto v = std::make_obj_using_allocator<V>(
    MyAlloc<int>{42}, std::make_pair(VEC{MyAlloc<int>(99)}, 1), 2
  );
  std::cout << v.first.first.get_allocator().state << '\n';
}

出力

42

バージョン

言語

  • C++20

処理系

関連項目

参照