2012-08-15 1 views
0

글쎄, 나는 템플릿을 공부하고, 나는 다음 코드에 문제가 삭제 : 내가 소멸자에 delete[] this->inst;을 넣을 때이 있지만 작동는 [] 소멸자

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

을, 나를 던졌습니다 어설 션 실패, 그리고 왜 ... 나는 destructor에서 리소스를 삭제하는 것이 나쁜가요?

답변

1

당신은 다음과 같은 방법 정의에 중복 식별자 n 있습니다

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

나는 위의 선언으로 컴파일 오류를 얻었다을, 당신이하지 않았다 놀랐어요. int n 중 하나의 이름을 다른 것으로 바꿔야합니다 (예 : Resize(int newsize)).

소멸자에서 inst 회원을 삭제해도 문제가 없습니다. 이것이 메모리 누출을 피하기 위해해야 ​​할 일입니다.

+0

고맙습니다.하지만 매개 변수의 이름을 변경했는데 작성시 해당 어설 션이 실패했습니다. delete [] this-> inst; 소멸자의 정의 – German

+0

매개 변수의 이름을 변경 한 후 코드가 작동했습니다. 네가받는 실제 메시지가 뭐야? (어설 션이 실패한 메시지는 일반적으로 * some * detail과 함께 나타납니다) –

+0

"Expression _BLOCK_TYPE_IS_VALID (pHead-> nBlockUse)"dbgdel.cpp 줄 : 52 – German