【问题标题】:delete[] in destructor析构函数中的删除[]
【发布时间】:2012-08-11 08:28:29
【问题描述】:

嗯,我正在研究模板,我对下一个代码有问题:

        #include <iostream>

        using namespace std;

        template<class T, int n>
        class Table
        {
        public:
            Table();
            //~Table();
            int& operator[](int i);
            bool Resize(int n);
            int Count();
            void Free();

        private:
            T* inst;
            int count;
        };

        template<class T, int n>
        Table<T, n>::Table()
        {
            inst = new T[n];
            count = n;
        }

        template<class T, int n>
        void Table<T, n>::Free()
        {
            delete[] this->inst;
        }

        template<class T, int n>
        int& Table<T, n>::operator[](int i)
        {
            return inst[i];
        } 

        template<class T, int n>
        bool Table<T, n>::Resize(int n)
        {
            this->inst = (T*)realloc(this->inst, sizeof(T)*count + sizeof(T)*n);
            if(!inst)
                return false;

            return true;
        }

        template<class T, int n>
        int Table<T, n>::Count()
        {
            return this->count;
        }

        template<typename T, int n> void ShowTable(Table<T, n> t)
        {
            for(int i=0; i<t.Count(); i++)
                cout<<t[i]<<endl;
        }

        int main()
        {
            Table<int, 2> table;
            table[0] = 23;
            table[1] = 150;
            ShowTable(table);

            system("pause");
            table.Free();

            return 0;
        }

它可以工作,但是当我将delete[] this-&gt;inst; 放入析构函数时,它会抛出一个断言失败,我不知道为什么......我的意思是,在析构函数中删除资源是不是很糟糕?

【问题讨论】:

    标签: c++ templates destructor delete-operator


    【解决方案1】:

    您在以下方法定义中有重复的标识符n

        template<class T, int n>
        bool Table<T, n>::Resize(int n)
    

    我在编译上述声明时遇到错误,我很惊讶你没有。您需要将其中一个int n 重命名为其他名称(例如Resize(int newsize))。

    在析构函数中删除inst 成员没有问题。这就是你应该做的,以避免内存泄漏。

    【讨论】:

    • 谢谢,但我更改了该参数的名称,但当我写入时,我仍然认为断言失败:delete[] this->inst;在析构函数的定义中
    • 您的代码在更改参数名称后对我有用。你得到的实际信息是什么? (断言失败消息通常带有一些细节)
    • 它抛出了“Expression _BLOCK_TYPE_IS_VALID(pHead->nBlockUse)”dbgdel.cpp line: 52
    • 我意识到问题出在 ShowTable 方法中(因为如果我在 main 方法中使用 cout 显示表值,则不会出现错误)但我不知道哪里错了跨度>
    • 我看到了问题。您正在通过值将表传递给ShowTable(),但尚未为Table 类定义合适的复制构造函数。因为您的类中有一个普通指针,所以您必须定义一个复制构造函数(和赋值运算符),它会复制inst 数据。要查看问题,请在析构函数上设置断点,然后查看它尝试删除同一块内存的次数。
    猜你喜欢
    • 2015-09-24
    • 2017-04-06
    • 2013-04-27
    • 2012-03-13
    • 2013-10-01
    • 2014-12-30
    • 1970-01-01
    • 2020-10-18
    • 1970-01-01
    相关资源
    最近更新 更多