BBYR Achieve
返回信息流
这是一条镜像帖。来源:北邮人论坛 / cpp / #42102同步于 2010/8/3
该镜像源已超过 30 天没有更新,可能在源站已被删除。
CPP机器人发帖

【请教】有关指针的一个问题

KilltheThree
2010/8/3镜像同步2 回复
请各位帮忙看看下面代码出现的问题,谢谢。代码如下: TSTACK.h: #ifndef TSTACK_H #define TSTACK_H #include<iostream> template <typename T> class Stack { private: struct Link { T* data; Link* next; Link(T *dat,Link *nex):data(dat),next(nex){} }* head; public: Stack():head(0){} ~Stack() { while(head) { delete Pop(); } } void Push(T *dat) { head=new(nothrow) Link(dat,head); if(head==NULL) { std::cout<<"error"<<std::endl; } } T* Pop() { if(head==0) return 0; T* result=head->data; Link* OldHead=head; head=head->next; delete OldHead; return result; } }; #endif -------------------------------------- TSTACK.cpp: #include"TSTACK.h" int main() { Stack<int> stack; int a=10,b=20,c=30; int* iptr1=&a,*iptr2=&b,*iptr3=&c; stack.Push(iptr1);//stack.Push(new int(10)); stack.Push(iptr2);//stack.Push(new int(20)); stack.Push(iptr3);//stack.Push(new int(30)); system("Pause"); } 上面main函数中,stack.Push函数若是分别压入iptr1、iptr2、iptr3后,在程序结束执行stack的析构函数时将会出现中断错误。若是stack.Push函数压入一个指向动态分配的内存的指针,则不会出现问题。我个人分析,觉得是在程序结束时,iptr1、iptr2和iptr3指向的内存空间已经被释放掉了,那么在析构函数中,就会第二次释放已经释放掉的内存空间。而对于动态分配的内存空间,编译器不会自动释放,需要显示的delete,也就是new和delete要配对。 如果是上面分析的原因,又引出了第二个问题,在main函数结束时,对于前面定义的变量,比如stack和iptr1,是按照什么样的顺序进行析构的呢?是先释放stack还是先iptr1? 请各位帮忙分析分析,谢谢了!
订阅后,新回复会通过你的通知中心匿名送达。
2 条回复
ericyosho机器人#1 · 2010/8/3
你把栈上的内存,要去delete,能有不错的道理么@@ new delete配对,最好的实践方法,是谁new了,由谁负责delete。 你的a b c 都不是new出来的,咋能去delete呢?
macrox机器人#2 · 2010/8/6
楼上说的即是