memory_allocator
memory_allocator (std::allocator)
<memory> 헤더에 정의되어 있어요. 모든 표준 라이브러리 컨테이너가 사용자 지정 할당자를 주지 않으면 기본으로 사용하는 Allocator 클래스 템플릿이에요. 기본 할당자는 무상태(stateless)라서, 같은 타입의 모든 인스턴스가 서로 교체 가능하고 동등하게 비교되며 같은 타입의 다른 인스턴스가 할당한 메모리도 해제할 수 있어요.
출처: cppreference
본문
template< class T >
struct allocator; // (1)
template<>
struct allocator<void>; // (2) deprecated in C++17, removed in C++20
void에 대한 명시적 특수화는 reference, const_reference, size_type, difference_type 멤버 typedef가 없어요. 이 특수화는 멤버 함수를 선언하지 않아요. (C++20 이전) 기본 할당자는 할당자 완전성 요구사항을 만족해요. (C++17)
멤버 타입
| 타입 | 정의 |
|---|---|
value_type |
T |
pointer (C++17에서 deprecated, C++20에서 제거) |
T* |
const_pointer (deprecated, removed) |
const T* |
reference (deprecated, removed) |
T& |
const_reference (deprecated, removed) |
const T& |
size_type |
std::size_t |
difference_type |
std::ptrdiff_t |
propagate_on_container_move_assignment (C++11) |
std::true_type |
rebind (deprecated, removed) |
template< class U > struct rebind { typedef allocator<U> other; }; |
is_always_equal (C++11, C++23 deprecated, C++26 removed) |
std::true_type |
멤버 함수
생성자·소멸자, allocate(초기화되지 않은 저장 공간 할당), allocate_at_least(C++23, 요청 크기 이상 할당), deallocate(저장 공간 해제), 그리고 C++20 이전의 address, max_size, construct, destroy가 있어요.
예제
#include <iostream>
#include <memory>
#include <string>
int main()
{
std::allocator<int> alloc1;
static_assert(std::is_same_v<int, decltype(alloc1)::value_type>);
int* p1 = alloc1.allocate(1); // int 하나 공간
alloc1.deallocate(p1, 1); // 해제
using traits_t1 = std::allocator_traits<decltype(alloc1)>;
p1 = traits_t1::allocate(alloc1, 1);
traits_t1::construct(alloc1, p1, 7); // int 구성
std::cout << *p1 << '\n';
traits_t1::deallocate(alloc1, p1, 1);
std::allocator<std::string> alloc2;
using traits_t2 = std::allocator_traits<decltype(alloc2)>;
std::string* p2 = traits_t2::allocate(alloc2, 2);
traits_t2::construct(alloc2, p2, "foo");
traits_t2::construct(alloc2, p2 + 1, "bar");
std::cout << p2[0] << ' ' << p2[1] << '\n';
traits_t2::destroy(alloc2, p2 + 1);
traits_t2::destroy(alloc2, p2);
traits_t2::deallocate(alloc2, p2, 2);
}
출력:
7
foo bar
주의 (Notes)
rebind 멤버 템플릿은 다른 타입용 할당자를 얻는 방법을 제공해요. 예를 들어 std::list<T, A>는 std::allocator_traits<A>::rebind_alloc<Node<T>>를 통해 내부 타입 Node<T>의 노드를 할당해요. is_always_equal은 LWG 3170으로 deprecated됐어요.