방금 new 및 delete 연산자를 재정의하는 개인 프로젝트를 완료했으며 그 과정에서 할당 자 클래스에 대해 배우게되었습니다. cppreference.com을 비롯한 여러 온라인 참조 서를 읽은 후에 많은 기능이 선택적으로 설명됩니다.많은 할당 기 기능이 선택적입니까?
제 질문은 어떻게 할당 자 수신자입니까? std::set
, 수신 된 할당자가 선택적으로 함수와 유형을 구현하는 경우 작동합니까?
allocator가 모든 함수에 대한 기본 구현을 가진 기본 클래스에서 파생되어야하지만 할당 자에 대한 상속 요구 사항이 없는지 이해할 수 있습니다.
아니면 컴파일 오류로 이러한 선택적 기능을 구현할 필요성에 대해 경고를 받겠습니까?
참고로 여기는 std::set
에 대한 세 번째 템플릿 인수로 사용한 할당 자에 대한 나의 첫 번째 시도입니다. 나는 기존의 예제를 수행했기 때문에, 구현 한 많은 것들이 불필요하다고 생각하지만, 앞으로 다른 STL 컨테이너에서 할당자를 사용하기로 결정할 때 판단 방법을 이해하지 못한다. 다시 말하면, 컴파일 에러를 기반으로 그것을 파악하는 것이 아니라면 ...?
template <typename T>
class Allocator // Custom allocator for use by AllocSet::mAllocatedPtrs to avoid infinite recursion
{ // (because inserting an element in std::set calls ::operator new, which is overridden to add to AllocSet::mAllocatedPtrs).
public:
typedef T value_type;
typedef T* pointer;
typedef T& reference;
typedef const T* const_pointer;
typedef const T& const_reference;
typedef size_t size_type;
typedef ptrdiff_t difference_type;
template <typename U>
struct rebind { typedef Allocator<U> other; };
Allocator() { }
template <typename U> Allocator(const Allocator<U>&) { }
virtual ~Allocator() { }
pointer allocate(size_t numT) { return (T*)(malloc(numT * sizeof(T))); }
void deallocate(pointer p, size_type st) { free(p); }
size_type max_size() { return size_type(-1); }
reference operator=(const_reference) { return *this; }
template <typename U> reference operator=(const Allocator<U>&) { return *this; }
template <typename U> bool operator==(const Allocator<U>&) { return true; }
template <typename U> bool operator!=(const Allocator<U>&) { return false; }
pointer address(reference r) { return &r; }
const_pointer address(const_reference r) { return &r; }
};
나는 이해한다 : allocator 사용자는 사용자 생성 할당 자에서 구현되지 않은 한 std :: allocator_traits를 기본적으로 사용한다. 맞다. 그렇다면 이것은 다형성처럼 들립니다. 이 할당 자 개념이 인터페이스/구현 방식 대신이 방식으로 구현 된 이유는 알고 있습니까? – StoneThrow
@StoneThrow 정확하지 않음 : 할당 자의 사용자는 무조건'std :: allocator_traits'를 사용해야합니다.'std :: allocator_traits'는 할당자가 물건을 제공하는지 아닌지를 "파악"합니다. 예, [여기] (http://stackoverflow.com/questions/257288/is-it-possible-to-write-ac-template-to-check-for-a-functions-existence)를 확인하는 방법' max_size()'가 존재합니다. –
고맙습니다. 다시 말하면,이 접근법이 클래스 기반 다형성 대신에 취해진 이유는 무엇입니까? 저는 최근에 템플릿 기반 코딩에 들어가기 시작 했으므로 장단점과 추론에 대해 궁금합니다. – StoneThrow