c++ simple "Garbage Collector"

The idea is to create a Ptr type that acts like a reference in Java.

And A Garbage Collector (MemMgr) type that acts like a garbage collector in Java.

Just a toy. :D

main.cpp

 1 #include "MemMgr.h"
 2
 3 #include <iostream>
 4
 5 using namespace std;
 6
 7 class Box
 8 {
 9     public:
10         void dosomething() { cout << "Box dosomething" << endl; }
11         Box() { cout << "Box cons" << endl; }
12         ~Box() { cout << "Box des" << endl; }
13 };
14
15 Ptr<Box> global;
16 MemMgr mgr;
17
18
19 Ptr<Box> func() {
20     Ptr<Box> pb = mgr.regist(new Box());
21     return pb;
22 }
23
24
25
26 int main()
27 {
28     Ptr<Box> p = func();
29     p->dosomething();
30     (*p).dosomething();
31     Ptr<Box> p2 = p;
32     p2->dosomething();
33     cout << "end of main" << endl;
34     global = p2;
35     return 0;
36 }

MemMgr.h

  1 #ifndef MEMMGR_H
  2 #define MEMMGR_H
  3
  4 #include <map>
  5 #include <cstdlib>
  6 #include <set>
  7
  8 template <typename TYPE>
  9 class Ptr;
 10
 11 /**
 12     MemMgr take the idea of Garbage Collector
 13     from the Java language. It‘s just much simple
 14     and limited.
 15 */
 16 class MemMgr
 17 {
 18     template <typename T> friend class Ptr;
 19     private:
 20         typedef unsigned long count;
 21         template <typename T> void login(T* ptr_obj);
 22         template <typename T> void logout(T* ptr_obj);
 23         std::map<void*, count> cmap;
 24     public:
 25         MemMgr();
 26         /**
 27             Client is responsible to ensure obj is in the heap,
 28             and make sure only use Ptr objects rather than ordinary
 29             pointers when manipulating objects managed by MemMgr.
 30
 31             If MemMgr is destroyed before any Ptr object managed
 32             by it, all Ptr objects managed by that MemMgr are all
 33             dangled pointers, this eventually leads to memory leak.
 34             So it‘s crucial to make sure MemMgr is not destroyed
 35             before ALL Ptr objects managed by it are destroyed.
 36
 37             Otherwise the behavior of the MemMgr is undefined.
 38         */
 39         template <typename T> Ptr<T> regist(T *obj);
 40         ~MemMgr();
 41
 42 };
 43
 44 /**
 45     Ptr acts like a reference in java.
 46 */
 47 template <typename TYPE>
 48 class Ptr {
 49
 50     friend class MemMgr;
 51
 52     public:
 53         Ptr& operator=(const Ptr<TYPE> &copy)
 54         {
 55             if(copy) {
 56                 logout();
 57                 obj = copy.obj;
 58                 mgr = copy.mgr;
 59                 copy.mgr->login(&obj);
 60             } // else leaves obj and mgr NULL
 61             return *this;
 62         }
 63         TYPE* operator->() { return obj; }
 64         TYPE& operator*() { return *obj; }
 65         const TYPE* operator->() const { return obj; }
 66         const TYPE& operator*() const { return *obj; }
 67         operator bool() const { return ( (obj != NULL) && (mgr != NULL) ); }
 68
 69         Ptr(): obj(NULL), mgr(NULL) {}
 70         Ptr(const Ptr &copy): obj(NULL), mgr(NULL)
 71         {
 72             if(copy) {
 73                 obj = copy.obj;
 74                 mgr = copy.mgr;
 75                 copy.mgr->login(obj);
 76             }
 77         }
 78         ~Ptr()
 79         {
 80             logout();
 81         }
 82     private:
 83         Ptr(TYPE *_obj, MemMgr *_mgr): obj(_obj), mgr(_mgr)
 84         {
 85             mgr->login(obj);
 86         }
 87         void logout() {
 88             if (*this) {
 89                 mgr->logout(obj); obj = NULL; mgr = NULL;
 90             }
 91         }
 92         TYPE *obj;
 93         MemMgr *mgr;
 94 };
 95
 96
 97 template <typename T> Ptr<T> MemMgr::regist(T *obj)
 98 {
 99     return Ptr<T>(obj, this);
100 }
101
102 template <typename T>
103 void MemMgr::login(T* ptr_obj)
104 {
105     std::map<void*, count>::iterator iter = cmap.find(ptr_obj);
106     if (iter != cmap.end()) {
107         ++(iter->second);
108     } else {
109         cmap.insert(std::pair<void*, count>(ptr_obj, 1));
110     }
111 }
112
113 template <typename T>
114 void MemMgr::logout(T* ptr_obj)
115 {
116     std::map<void*, count>::iterator iter = cmap.find(ptr_obj);
117     if (iter != cmap.end()) {
118         --(iter->second);
119         if (iter->second == 0) {
120             T *p = (T*)(iter->first);
121             delete p;
122         }
123     }
124 }
125
126 #endif // MEMMGR_H

MemMgr.cpp

 1 #include "MemMgr.h"
 2
 3 #include <iostream>
 4
 5 using namespace std;
 6
 7 MemMgr::MemMgr()
 8 {
 9     cout << "MemMgr cons" << endl;
10 }
11
12 MemMgr::~MemMgr()
13 {
14     cout << "MemMgr des" << endl;
15 }
时间: 2024-08-09 20:54:35

c++ simple "Garbage Collector"的相关文章

agc 027 B - Garbage Collector

B - Garbage Collector https://agc027.contest.atcoder.jp/tasks/agc027_b 题意: x坐标轴上n个垃圾,有一个机器人在从原点,要清扫垃圾.原点有一个垃圾桶.机器人可以在x轴上左右移动,当移动到某个垃圾的位置上时,可以选择花费 X 点能量将它捡起来(也可以视而不捡).机器人如果到达垃圾桶,则可以将它携带的垃圾花费 X 点能量倒出.机器人如果携带着 K 件垃圾移动一个单位距离,则需要消耗 (K+1)^2 点能量.问将所有垃圾全部弄到垃

The Go Blog Getting to Go: The Journey of Go&#39;s Garbage Collector

Getting to Go: The Journey of Go's Garbage Collector https://blog.golang.org/ismmkeynote The Go Blog Getting to Go: The Journey of Go's Garbage Collector 原文地址:https://www.cnblogs.com/yuanjiangw/p/12179561.html

G1 Garbage Collector and Shenandoah

http://www.diva-portal.se/smash/get/diva2:754515/FULLTEXT01.pdf https://is.muni.cz/th/ifz8g/GarbageCollection.pdf?so=nx https://www.researchgate.net/publication/306112816_Shenandoah_An_open-source_concurrent_compacting_garbage_collector_for_OpenJDK h

garbage collection - 垃圾收集

Professional.JavaScript.for.Web.Developers.3rd.Edition.Jan.2012 JavaScript is a garbage-collected language, meaning that the execution environment is responsible for managing the memory required during code execution. In languages like C and C++, kee

Oracle JVM Garbage Collectors Available From JDK 1.7.0_04 And After

Jack Shirazi tells you what garbage collectors and garbage collector combinations are available from the Oracle Java 7 update 4 JVM and onwards, including Java 8 and Java 9. Published June 2012, Updated September 2015, Author Jack Shirazi --From http

Tuning Java Garbage Collection for Spark Applicati

This is a guest post from our friends in the SSG STO Big Data Technology group at Intel. Join us at the Spark Summit to hear from Intel and other companies deploying Spark in production.  Use the code Databricks20 to receive a 20% discount! Spark is

A SIMPLE LIBRARY TO BUILD A DEEP ZOOM IMAGE

My current project requires a lot of work with Deep Zoom images. We recently received some very high-res photos, around 500M tiff files, some of which Deep Zoom Composer was unable to process. My first thought was to split them into smaller pieces an

Java_garbage collector

摘自:http://blog.csdn.net/java2000_wl/article/details/8030172 HotSpot JVM垃圾收集器 上面有7中收集器,分为两块,上面为新生代收集器,下面是老年代收集器.如果两个收集器之间存在连线,就说明它们可以搭配使用. Serial(串行GC)收集器_Serial GC Serial收集器是一个新生代收集器,单线程执行,使用复制算法.它在进行垃圾收集时,必须暂停其他所有的工作线程(用户线程).是Jvm client模式下默认的新生代收集器.

Understanding .net CLR garbage collection--(踏踏实实学好.Net系列)

引言 内存管理是计算机科学中一个相当复杂而有趣的领域.在计算机诞生的这几十年间,内存的管理的技术不断进步,使系统能够更加有效地利用内存这一计算机必不可少的资源. 一般而言,内存管理可以分为三类:硬件管理(如TLB),操作系统管理(如Buddy System,Paging,Segmentation),应用程序管理(如C++,Java,.net的内存管理机制).鉴于篇幅和笔者水平的限制,本文只涉及了内存管理的很小一部分,即.net中的内存管理方法..net是一个当代的应用程序框架,采用了内存自动管理