【问题标题】:Deallocating with std::allocator用 std::allocator 解除分配
【发布时间】:2017-01-30 21:44:13
【问题描述】:

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

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

为了测试我的数组,我创建了一个简单的 Test 类,它只跟踪它存在的实例数,每次调用构造函数或复制构造函数时,都会增加一个名为 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
    }
}

我的预期输出是0, 1, 0, 2, 0, 3, 0, 4...,这意味着在范围开始时不存在任何TestObject,然后在数组中分配正确数量的对象,并在范围结束时销毁它们。相反,我得到了0, 1, 1, 2, 2, 3, 3, 4, 4... 的输出,这表明元素由于某种原因没有被正确销毁。就像元素仅在分配新元素时才被释放,但这不是我想要的行为。此外,在for 循环之外,instance_count 等于 100,这意味着即使在没有更多 Array 实例之后仍有剩余的对象。有人可以向我解释为什么std::allocator 没有正确清理元素吗?

【问题讨论】:

  • TestObject 看起来像什么?如果您使用std::vector&lt;TestObject&gt; 而不是Array&lt;TestObjecct&gt;,您的输出是什么?

标签: c++ arrays stl dynamic-memory-allocation allocator


【解决方案1】:

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

要创建对象,您需要调用 allocateconstruct

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-06-18
    • 2016-08-19
    • 1970-01-01
    • 2011-12-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多