使用模板时双重免费或损坏

时间:2014-08-31 20:12:27

标签: c++ templates runtime-error destructor

运行下面的代码后,我收到运行时错误“double free or corruption”。

如果我摆脱了析构函数内容(删除),它可以正常工作。怎么了?

析构函数中的消息帮助我发现它与变量元素的析构函数有关,但我知道如何解决它。

#include <stdio.h>
#include <inttypes.h>
#include <string.h>
/// First test class
class test_t {
    public:
    uint16_t *number;
    uint16_t& get_number(){return number[0];};

    test_t(){number = new uint16_t[16];};
    ~test_t(){
        printf("DESTOY test\n");
        delete [] number;
        };

    test_t& operator=(const test_t& other){
        if (this != &other) {
            memcpy( number, other.number, 16 );
        }
        return *this;
    }
};

/// Circular Buffer template
template <class CB_TYPE>
class circular_buffer_t
{
    public:
        /// Control variables
        uint32_t beg_index, end_index, size, capacity;
        CB_TYPE *data;

        /// Methods
        circular_buffer_t(){
            this->beg_index = 0;
            this->end_index = 0;
            this->size = 0;
            this->capacity = 0;

            this->data = NULL;
        };

        ~circular_buffer_t(){
            printf("DESTOY CB\n");

            if (this->data != NULL) {
                delete []data;
            }
        };

        CB_TYPE& operator[](uint32_t index){
            uint32_t position = this->beg_index + index;
                if (this->end_index >= this->capacity) position = 0;

            return data[index];
        };

        CB_TYPE operator[](uint32_t index) const {
            uint32_t position = this->beg_index + index;
                if (this->end_index >= this->capacity) position = 0;

            return data[index];
        };

        void allocate(uint32_t elements){
            this->capacity = elements;
            this->data = new CB_TYPE[this->capacity];
            if (this->data == NULL)
                printf("Could not allocate the circular buffer size.\n");
        };


        int32_t push_back(CB_TYPE new_element){
            int32_t virtual_position = -1;

            this->size++;
            memcpy(&this->data[end_index], &new_element, sizeof(CB_TYPE));

            this->end_index++;
            if (this->end_index >= this->capacity) this->end_index = 0;

            virtual_position = this->size - 1;

            return virtual_position;
        };
};


int main()
{
    circular_buffer_t<test_t> cb;
    cb.allocate(10);

    {
        test_t element;
        cb.push_back(element);
    } // This emulates the call for the destructor from "element"


    printf("done %d", cb[0].get_number() );
    return 1;
}

0 个答案:

没有答案