C++ 取消分配std::分配器

C++ 取消分配std::分配器,c++,arrays,stl,dynamic-memory-allocation,allocator,C++,Arrays,Stl,Dynamic Memory Allocation,Allocator,我一直在尝试编写自己的STL容器实现以供实践,但在释放元素时遇到了一些问题。我创建了一个简单的数组类,它基本上是标准C++数组的包装器。我一直试图实现的一个重大变化是,如果数组没有默认构造函数,就允许对其进行初始化(我知道Vectors可以做到这一点,但我想练习实现它)。由于这个特性,我不能使用new,所以我决定让容器使用类似标准STL容器的分配器。数组看起来有点像这样: template<class T, class A = std::allocator<T>> cla

我一直在尝试编写自己的STL容器实现以供实践,但在释放元素时遇到了一些问题。我创建了一个简单的<代码>数组类,它基本上是标准C++数组的包装器。我一直试图实现的一个重大变化是,如果数组没有默认构造函数,就允许对其进行初始化(我知道Vectors可以做到这一点,但我想练习实现它)。由于这个特性,我不能使用
new
,所以我决定让容器使用类似标准STL容器的分配器。
数组
看起来有点像这样:

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

我的预期输出是
0,1,0,2,0,3,0,4…
,这意味着在作用域开始时不存在TestObject,然后在数组中分配正确数量的TestObject,并在作用域结束时销毁它们。相反,我得到了
0,1,1,2,2,3,3,4,4…
的输出,这表明元素由于某种原因没有被正确销毁。就像只有在分配新元素时才释放元素,但这不是我想要的行为。此外,在
for
循环之外,
实例计数
等于100,这意味着即使不再有
数组
的实例,仍有剩余的对象。有人能给我解释一下为什么
std::allocator
没有正确地清理元素吗?

因为你没有破坏对象,只是释放了它们占用的内存。分配器将分配/解除分配(使用
分配
解除分配
)和构造/销毁(使用
构造
销毁
)的概念分开

要创建对象,您需要调用
分配
构造


要销毁对象,您需要调用
destroy
,然后
deallocate

,因为您没有销毁对象,只是释放了对象占用的内存。分配器将分配/解除分配(使用
分配
解除分配
)和构造/销毁(使用
构造
销毁
)的概念分开

要创建对象,您需要调用
分配
构造


要销毁对象,您需要调用
destroy
,然后
deallocate

测试对象的外观是什么?如果使用
std::vector
而不是
Array
,您的输出是什么?
TestObject
看起来像什么?如果使用
std::vector
而不是
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
    }
}