0

好吧,我正在研究模板,但我对下一个代码有疑问:

        #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->inst;析构函数时,它会抛出一个断言失败,我不知道为什么......我的意思是,删除析构函数中的资源是不是很糟糕?

4

1 回答 1

1

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

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

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

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

于 2012-08-15T00:21:32.823 回答