std::allocator

Minjun_·2022년 8월 15일

C++

목록 보기
2/5
post-thumbnail

std::allocator

#include <memory>

template <class T>
class allocator;

Allocators are classes that define memory models to be used by some parts of the Standard Library, and most specifically, by STL containers.
STL 라이브러리에서 많이 사용되는 메모리 할당 방식

Member types

memberdefinition in allocatorrepresents
value_typeTElement type
pointerT*Pointer to element
referenceT&Reference to element
const_pointerconst T*Pointer to element
const_referenceconst T&Reference to const element
size_typesize_tQuantities of elements
difference_typeptrdiff_tDifference between two pointers
rebindmember classIts member type other is the equivalent allocator type to allocate elements of type Type

size_t

Unsigned integral type

해당 시스템에서 어떤 객체나 값이 포함할 수 있는 최대 크기의 데이터를 표현하는 타입

ptrdiff_t

Result of pointer subtraction

It is a type able to represent the result of any valid pointer subtraction operation.
pointer 연산시 나오는 결과값을 모두 담을 수 있는 자료형

일반적으로 C++에서 메모리를 동적으로 할당하고 해제할 때 new / delete 연산자를 사용하는데, allocator 클래스는 주로 라이브러리를 작성할 때, STL 컨테이너를 구현할 때 많이 사용된다.

allocator는 메모리 관리를 좀 더 세밀하게 컨트롤하고 효율적으로 사용해야 할 경우 유저가 원하는 메모리 할당 방식으로 구현할 수 있다.

→ allocator class를 상속받아 멤버함수를 override 할 수 있다.

Container는 메모리를 효율적으로 관리해야 하는데, new / delete 연산자로는 세밀한 메모리 관리 능력이 떨어진다.

Container는 데이터를 저장하고 관리하는 공간이다. 따라서 저장 공간의 생성, 확장, 추가, 삭제 등이 빈번하게 발생한다. 이 과정에서 new / delete 연산자를 사용할시 다음과 같은 문제점이 발생한다.

  • 기본 생성자 필요
  • 메모리 할당
  • 모든 요소 초기화

allocator 클래스를 사용하면 위 단계들을 원할 때 사용할 수 있다.

allocator 사용시 장점

  • 메모리를 동적 할당할 경우 초기화되지 않은 공간(uninitialized)으로 메모리를 allocate 할 수 있다. new 연산자는 메모리를 할당하고 기본적으로 값 또는 객체를 초기화 해준다. (오버헤드 발생) allocator의 멤버 함수를 이용하면 메모리의 할당은 되었지만 초기화는 되지 않은 상태의 메모리 시작 주소를 얻을 수 있음.
  • 할당 받은 메모리에 객체를 생성 후 메모리 해제(deallocate) 없이 생성한 객체들을 소멸(destroy)시킬 수 있다. 즉, 메모리의 재할당 없이 그 공간을 allocate 했던 초기 상태로 만들 수 있다.
template <class T>
class allocator
{
public:
   T* allocate(size_t);
   void deallocate(T*, size_t);
   void construct(T*, const T&);
   void destory(T*);
   ....
};

template <class In, class For>
For uninitialized_copy(In, In, For);

template <class For, class T>
void uninitialized_fill(For, For, const T&);

Member Functions

address

pointer address ( reference x ) const;
const_pointer address ( const_reference x ) const;

Returns the address of *x.

allocate

pointer allocate (size_type n, allocator<void>::const_pointer hint=0);

Release block of storage

초기화되지 않은 메모리 공간을 할당하여 그 시작 주소를 반환하는 함수

매개변수는 바이트 단위가 아닌 필요한 T 객체의 개수(n)이다.

인자로 전달된 개수만큼 T타입의 객체를 충분히 할당할 수 있는 공간을 만든다.

deallocate

void deallocate (pointer p, size_type n);

Release block of storage

메모리 공간을 해제하는 함수

배열 안에 있는 elements 들은 destroy 되지 않는다.

인자로 포인터와 개수를 받으며, 포인터는 allocate로 할당했던 메모리의 시작 주소를 가리키는 포인터, 개수는 allocate로 전달했던 인자의 개수

cpp reference에는 반드시 allocate로 전달했던 인자의 개수와 동일해야 한다고 나와 있음.

max_size

size_type max_size() const throw();

Maximum size possible to allocate

allocate 메소드를 이용하여 할당할 수 있는 최대 element의 개수 (value type) 를 반환한다.

이 개수를 가지고 allocate를 호출해도 실패할 가능성이 있음.

construct

void construct ( pointer p, const_reference val );

Constructs an element object on the location pointed by p.

Notice that this does not allocate space for the element. It should already be available at p

초기화되지 않은 공간에 요소를 저장하는 함수

T타입의 포인터와 객체의 레퍼런스를 받으며 포인터가 가리키는 위치에 객체를 저장한다.

destroy

void destroy (pointer p);

Destroys in-place the object pointed by p.

T타입 포인터를 인자로 받으며 포인터가 가리키는 위치의 객체의 소멸자를 호출한다.

인자로 전달된 포인터가 가리키는 객체의 소멸자를 호출한다.

destroy를 호출하지 않고 deallocate를 호출할 경우 각 요소에 저장된 객체는 사라지지만 사라진 객체가 가리키던 객체는 그대로 메모리에 남아있어 메모리 누수가 발생할 수 있다.

uninitialized_copy

STL의 std::copy와 비슷하며, 입력 iterator 2개와 forward_iterator 1개를 인자로 받는다. [first, last) 범위의 요소들을 out이 가리키는 위치에 순서대로 복사.

복사가 완료된 위치의 다음 요소를 가리키는 포인터를 반환한다.

uninitialized_fill

주어진 범위의 공간을 3번째 인자로 주어진 값으로 채운다.

profile
졸음을 이겨내자..!

0개의 댓글