[英]delete[] in destructor
好吧,我正在研究模板,並且下一個代碼有問題:
#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;
放入時delete[] this->inst;
在析構函數中,它使我斷言失敗,我不知道為什么...我的意思是,刪除析構函數中的資源是否不好?
在以下方法定義中,您具有重復的標識符n
:
template<class T, int n>
bool Table<T, n>::Resize(int n)
使用上述聲明進行編譯時出現錯誤,很奇怪您沒有這樣做。 您將需要將int n
之一重命名為其他名稱(例如Resize(int newsize)
)。
刪除析構函數中的inst
成員沒有問題。 那是您應該采取的避免內存泄漏的措施。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.