私は実際に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
は、要素を正しくクリーンアップしていないのですか?
'TestObject'はどのように見えますか? 'Array'の代わりに 'std :: vector 'を使うと、あなたの出力は何ですか? –
1201ProgramAlarm