STL Allocator

강보석·2024년 3월 20일

우리가 앞에서 배웠던 Allocator들은 동적할당을 할 때 어떤 추가옵션을 넣어둔 기능들입니다.
우리가 자주 쓰는 STL도 동적할당을 해서 만들어진 것입니다. 그렇기에 우리가 만들어둔 Allocator들을 인자로 주어 STL을 만들 때 동적할당을 어떻게 할지도 우리가 정해줄 수 있습니다.

template<typename T>
class STLAllocator {
public:
	using value_type = T;

	STLAllocator() {}

	template<typename Other>
	STLAllocator(const STLAllocator<Other>&) {}

	T* allocate(size_t count) {
		int32 size = static_cast<int32>(count * sizeof(T));
		return static_cast<T*>(xxalloc(size));
	}

	void deallocate(T* ptr, size_t count) {
		xxrelease(ptr);
	}
};

int main() {
	vector<int, STLAllocator<int32>> v(100);
}

이런 식으로 하면 될 것입니다.
참고로 STL에서 원하는 Allocator 형식이 있기에 이에 따라 만들어줘야 합니다.

profile
안녕하세요. 컴퓨터를 공부하는 학생입니다.

0개의 댓글