2017-01-30 5 views
0

私は実際にSTLのコンテナの実装を記述しようとしていましたが、私の要素の割り当てを解除するのに問題があります。基本的に標準のC++配列のラッパーである単純なArrayクラスを作成しました。私が実装しようとしてきた大きな変化は、デフォルトのコンストラクタがない場合に配列を初期化できることです(私はVectorsがこれを行うことができますが、実装を練習したいと思っています)。この機能のために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が適切に作成し、要素を破壊したことを主張するために、以下の方法を書いた:

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 
    } 
} 

私の予想出力は何TestObjectsが存在しない範囲の先頭に、その後、それらの正確な量があることを意味し0, 1, 0, 2, 0, 3, 0, 4...です配列に割り当てられ、スコープの終わりに破棄されます。代わりに、何らかの理由で要素が正しく破棄されていないことを示す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を呼び出してください。

オブジェクトを破棄するには、destroyと、次にdeallocateを呼び出す必要があります。

関連する問題