2017-01-30 2 views
0

연습용으로 STL의 컨테이너 구현을 직접 작성하려고했지만 내 요소를 할당 해제하는 데 문제가 있습니다. 기본적으로 표준 C++ 배열에 대한 래퍼 인 간단한 Array 클래스를 만들었습니다. 내가 구현하려고 시도한 큰 변화는 기본 생성자가 없으면 배열을 초기화 할 수 있다는 것입니다 (벡터가이 작업을 수행 할 수 있지만 구현을 연습하고 싶었 음을 알고 있습니다). 이 기능으로 인해 new을 사용할 수 없으므로 컨테이너에 표준 STL 컨테이너와 같은 할당자를 사용하도록 결정했습니다.std :: allocator를 사용하여 할당 해제

template<class T, class A = std::allocator<T>> class Array { 
    public: 
     // STL definitions and iterators... 

     /// initializes an array of size elements with all elements being 
     /// default constructed. 
     Array(const size_type &size) : Array(size, T()) { 

     } 

     /// Initializes an array of size elements with all elements being 
     /// copies of the fill element. 
     Array(const size_type &size, const T &fill) { 
      this->allocator = A(); // Get allocator from template 
      this->size = this->max_size = size; 

      // Allocate data array and copy the fill element into each 
      // index of the array. 
      this->data = this->allocator.allocate(size); 
      this->allocator.construct(this->data, fill); 
     } 

     /// Deletes the array and all of its elements. 
     ~Array() { 
      // deallocate using the allocator 
      this->allocator.deallocate(this->data, this->size); 
     } 

     // other things... 
} 

내 배열을 테스트하려면 단순히 생성자를, 그것의 때마다 생성자 존재하거나 복사 인스턴스의 수를 추적하는 간단한 테스트 클래스를 생성하는 것은 변수라고 다음 Array 조금 다음과 같습니다 instance_count이 증가되고 소멸자가 호출 될 때마다 변수가 감소합니다. 나는 다음 Array가 제대로 요소를 생성하고 파괴하는 것을 주장하기 위해 다음과 같은 방법을 썼다 :

내 예상 출력 범위의 시작 부분에 더 TestObjects 다음 중 올바른 양이, 존재하지 않는 것을 의미한다 0, 1, 0, 2, 0, 3, 0, 4...입니다
void testArray() { 
    for (int i = 1; i < 100; i++) { 
     std::cout << TestObject::instance_count << ", "; // should always == 0 
     Array<TestObject> testArray(i); // Create array of I elements 
     std::cout << TestObject::instance_count << ", "; // should == i 
    } 
} 

배열에 할당되고 범위 끝에서 삭제됩니다. 대신 출력이 0, 1, 1, 2, 2, 3, 3, 4, 4...인데, 이는 어떤 이유로 든 요소가 올바르게 파괴되지 않음을 나타냅니다. 새로운 요소가 할당 될 때 요소가 할당 해제되는 것처럼 보이지만, 원하는 동작이 아닙니다. 또한 for 루프 외부에서 instance_count은 100과 동일하므로 Array이 더 이상없는 경우에도 개체가 남아 있음을 의미합니다. 누군가 제발 내게 왜 std::allocator 요소를 올바르게 정리하지 않습니다 설명 할 수 있습니까?

+0

'TestObject'는 어떻게 생겼습니까? 'Array '대신'std :: vector '을 사용하면 출력은 어떻게됩니까? – 1201ProgramAlarm

답변

1

개체를 파괴하지 않으므로 개체가 차지하는 메모리를 확보하기 만하면됩니다. 할당자는 할당/할당 해제 (allocatedeallocate 사용) 및 구성/제거 (constructdestroy 사용)의 개념을 분리합니다.

개체를 만들려면 allocateconstruct을 호출해야합니다.

개체를 파괴하려면 destroydeallocate을 호출해야합니다.