Google v8 GC 垃圾回收的简易模拟

#include "stdafx.h" #include #include #include #include using namespace std; #define gc_trace printf class ObjPtr { public: void * _scope; void * _ptr; unsigned int _pv; }; static stack heaps; static void destory() { while(!heaps.empty()) { if (heaps.top()._ptr!=NULL) { gc_trace("delete ptr:%08X/n",heaps.top()._ptr); delete heaps.top()._ptr; } heaps.pop(); } } template //分配堆栈,并以堆栈顺序来排序 static T * New(unsigned int size) { ObjPtr optr; optr._ptr=new T[size]; optr._pv=0; optr._scope=0; if ( heaps.size()!=0 ) optr._scope=heaps.top()._scope; heaps.push(optr); gc_trace("new ptr:%08X/n",optr._ptr); return (T *)optr._ptr; } class HandleScope { public: bool _scope; //初始化,用堆栈指针作为分界 HandleScope() { ObjPtr optr; optr._ptr=NULL; optr._scope=&_scope; //获取堆栈指针,只有在此后面的对象才会被自动释放 heaps.push(optr); _scope=true; gc_trace("%08X/n",optr._scope); } void *close(void *rptr) { stack stk; while(!heaps.empty()) { if ( heaps.top()._ptr != NULL) { if ( rptr == heaps.top()._ptr) { stk.push(heaps.top()); }else{ gc_trace("delete ptr:%08X/n",heaps.top()._ptr); delete heaps.top()._ptr; } heaps.pop(); //如果指针为空,则表示对象为分界 }else{ heaps.pop(); break; } } //将返回的对象移交给上层处理 void * top_scope=NULL; if (heaps.size()!=0) top_scope=heaps.top()._scope; while(!stk.empty()) { gc_trace("move ptr:%08X/n",stk.top()._ptr); heaps.push(stk.top()); stk.pop(); } _scope=false; return rptr; } ~HandleScope() { if (!_scope) return; while(!heaps.empty()) { //如果指针为空,则表示对象 if (heaps.top()._ptr!=0) { gc_trace("delete ptr:%08X/n",heaps.top()._ptr); delete heaps.top()._ptr; heaps.pop(); }else{ heaps.pop(); break; } } _scope=false; } }; char * getstr(); void test_1(); int main(int argc, char* argv[]) { HandleScope hands; char *s=getstr(); printf("%s/n",s); destory(); system("pause"); return 0; } char * getstr() { //HandleScope hands; char *buff=New(1024); strcpy(buff,"hello"); return (char *)buff; }

你可能感兴趣的:(C++)