티스토리 뷰
C++에서 우리가 자주 쓰는 vector, map, queue 등, STL 자료구조는 원래 지정하지 않아도 자동으로 동적할당과 해제까지 다 해주는 아주 편리한 함수입니다. 여기서 이 자동으로 동적할당과 해제를 해주는 Allocator를 본인이 직접 작성하여 넣어줄 수도 있습니다.
vector를 호출할 때 인자를 살펴보게 되면 다음과 같이 두개의 인자를 받을 수 있는데, 첫번째는 클래스, 두 번째가 바로 Allocator 입니다.
template <class _Ty, class _Alloc = allocator<_Ty>>
class vector { // varying size array of values
이 allocator는 필수로 하는 함수가 두가지 있는데 그것은 allocate 와 deallocate 입니다. 다음은 강의의 예시입니다. 다음과 같이 allocate와 deallocate를 가지고 있고, 다음과 같은 형태로 인자로 넘겨줄 수 있습니다.
template<typename T>
class STLAllocator
{
public:
using value_type = T;
STLAllocator() { }
template<typename other>
STLAllocator(const STLAllocator<other>&) { }
T* allocate(size_t count);
void deallocate(T* ptr, size_t count);
};
vector<int, STLAllocator<int>> s;
그리고 저렇게 묶어줄 때는 using을 사용하면 쉽게 묶어줄 수 있습니다.
template<typename T>
using Vector = vector<T, STLAllocator<T>>;
와 같이 묶어 Vector<int> 와 같은 형태로 사용할 수 있도록 할 수 잇습니다.
'프로그래밍 언어 > C++' 카테고리의 다른 글
MemoryPool #1 (0) | 2023.04.05 |
---|---|
VirtualAlloc - PAGE 크기로 동적 할당 (0) | 2023.04.02 |
placement new문법(객체 초기화) (0) | 2023.03.27 |
shared_ptr 구현기 - 1일차 (0) | 2023.03.27 |
C++) STL 목차 정리 (0) | 2022.11.24 |
댓글