- 메모리 할당관련 함수를 추상화한 도구.
- 메모리 할당 방식을 쉽게 변경할 수 있게 한다.
allocator
- C++ 20 이후 부터는 construct / destroy 함수 제공 안함.
// Point Type으로 메모리 할당을 해주는 객체.
// 기본 구현은 operator new() / operator delete() 사용.
std::allocator<Point> ax;
// 할당. (생성자는 호출 안됨)
Point* p2 = ax.allocate(1);
// Point(0, 0) 생성자를 호출 (c++ 20부터 제공 안함)
ax.construct(p2, 0, 0);
// 소멸자 호출 (c++ 20부터 제공 안함)
ax.destroy(p2);
// 해제.
ax.deallocate(p2, 1);
// 메모리 할당자를 바꾸고 싶다면, ax만 커스텀 클래스로 바꾸어주면 된다.
ex) MyAlloc<Point> ax;
allocator traits
- 커스텀 Allocator에서 construct, destory가 구현되었다면 그것을 사용하고 아니라면 디폴트를 사용하도록 해주는 기능.
- 단, Custom Allocator에 value_type을 제공해야한다.
- ex) using value_type = T;
std::allocator_traits<MyAlloc<Point>>::construct(ax, p1, 0, 0);
std::allocator_traits<MyAlloc<Point>>::destory(ax, p1);