【发布时间】:2015-03-29 00:15:32
【问题描述】:
我不明白为什么 ListELement 的析构函数永远不会被调用。
我使用类 Base 作为计数器,ListELement 派生自 Base 以使用计数器。
节目:
#include <iostream>
#include <random>
#include <functional>
using namespace std;
class Base{
protected:
static int count;
};
template <class T>
class ListElement: public Base{
public:
ListElement(const T& value): next(NULL), data(value) { count++;}
~ListElement() { cout<<"dead:"<<count<<endl;}
//Setter
void SetData(const T& value) { data=value; }
void SetNext(ListElement* elem) { next = elem; }
//Getter
const T& GetData() const { return data; }
ListElement* GetNext() const { return next; }
private:
T data;
ListElement* next;
};
int Base::count = 0;
int main(){
random_device rd;
default_random_engine generator(rd());
uniform_int_distribution<int> distribution(1,100);
auto dice = bind(distribution, generator);
int nListSize = 1;
ListElement<int>* nMyList = new ListElement<int>(999);
ListElement<int>* temp = nMyList;//nMyList is the first element
for(int i=0; i<10; ++i) {
ListElement<int>* k = new ListElement<int>(dice()); //New element
temp->SetNext(k);
temp = temp->GetNext();
nListSize++;
}
temp=nMyList;
for(int i=0; i<nListSize; ++i){
cout<<"Value["<<i<<"]: "<<temp->GetData()<<endl;
temp = temp->GetNext();
}
return 0;
}
这是我的输出:
Value[0]: 999
Value[1]: 61
Value[2]: 14
Value[3]: 96
Value[4]: 51
Value[5]: 15
Value[6]: 37
Value[7]: 83
Value[8]: 1
Value[9]: 42
Value[10]: 95
如果我输入echo &?,控制台会返回我的0,所以一切都会好起来的。
【问题讨论】:
-
如果你用
new创建一个对象,你必须用delete手动销毁它。 -
好的!但是当程序退出时,它应该会破坏一切,对吧?
-
您也应该在遇到此类问题时使用
-Wall和-Werror运行编译。 -
当程序存在时,它会将内存释放回系统,它不会到处调用随机析构函数:)。