我正在学习c ++,并且在掌握内存管理的这方面有点困难。 对于我的任务,我必须制作一个类似堆栈的对象(可能有更有效的方法对此进行编码,但这并没有打扰我......) 我无法确定我是否正确释放了我的对象分配的内存:
template<typename dtp>
class cue{
class member{
member * next = NULL;
cue * parent;
public:
dtp data;
member(dtp d, cue * p)
{
parent = p;
data = d;
if(parent->last == NULL){parent->first = this; parent->last = this;}
else{parent->last->next = this; parent->last = this; }
}
~member(){
cout<<"deleting entry: "<<data<<endl;
parent->first = next;
}
};
member * first = NULL;
member * last = NULL;
public:
int s=0;
dtp back(){return last->data;}
dtp front(){return first->data;}
bool empty(){if(s == 0) return true; else return false;}
int size(){return s;}
void push(dtp input){
new member(input, this);
s++;
}
void pop(){
delete first;
s--;
}
~cue(){
cout<<"s="<<s<<endl;
while(s > 0){
this->pop();
}
}
};
我真的不明白是否需要成员的析构函数中的delete this;
(否则应该可以使用,因为成员只能由cue.push()
创建)..是delete last;
够了......或者说我完全错了?