0

Well, I'm studying templates and, I have a problem with the next code:

        #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;
        }

It works but, when I put the delete[] this->inst; in the destructor, it throws me an Assertion Failed, and I don't know why... I mean, is it bad to delete resources in a destructor?

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 に答える