[英]garbage collector c++
I've been trying to create a garbage collector in c++, i've designed it as a base class to all of mine, called garbageCandidate, which holds a static vector containing pointers to garbageCandidate with every garbageCollector instance pushing "this" on the vector. 我一直在尝试用c ++创建一个垃圾收集器,我把它设计为我的所有基类,叫做garbageCandidate,它包含一个静态向量,包含指向garbageCandidate的指针,每个garbageCollector实例都在向量上推送“this” 。
Then a static function comes and delete all the pointers in the static vector. 然后静态函数出现并删除静态向量中的所有指针。
At the very begining of the deleting function (delete on first pointer) i get an error stating delete was used on invalid pointer... 在删除函数的最开始(删除第一个指针)我得到一个错误,说明删除被用于无效指针...
Does this have to do with static/dynamic binding? 这与静态/动态绑定有关吗? I mean : is the delete operator unable to act as expected since i call delete on a "father" class and it is in fact a child ?
我的意思是:删除操作符是否无法按预期行事,因为我在“父”类上调用delete并且它实际上是一个孩子?
Could a way of avoiding this be to create virtual destructors? 一种避免这种情况的方法是创建虚拟析构函数吗? (or a virtual delete function)?
(或虚拟删除功能)?
or did i completely missed something? 还是我完全错过了什么?
ps:all objects used for test where created dynamically. ps:用于动态创建的测试的所有对象。
Is there a reason you're rolling your own custom garbage collector? 您是否有理由推出自己的自定义垃圾收集器? If all your objects are created dynamically, then why aren't you using boost's smart pointers (like boost::shared_ptr ) which essentially uses RAII to give you a well tested garbage collection solution?
如果所有对象都是动态创建的,那么为什么不使用boost的智能指针(如boost :: shared_ptr ),它本质上使用RAII为您提供经过良好测试的垃圾收集解决方案?
I ask because usually in the course of software development life cycle of a project, you end up fixing bugs in the code you wrote yourself (most of the time, at least). 我问,因为通常在项目的软件开发生命周期的过程中,你最终修复了你自己编写的代码中的错误(至少大部分时间)。 So is there a reason you're re-inventing the wheel?
那你有没有理由重新发明轮子?
Rather than rolling your own GC, I think you should be using the Boehm Conservative GC or smart pointers. 我认为您应该使用Boehm Conservative GC或智能指针,而不是滚动您自己的GC。 Neither is perfect:
两者都不完美:
The Boehm Collector requires you to use special allocate and (if you use it) deallocate methods, and getting existing libraries to play along can require some effort: Boehm Collector要求您使用特殊分配和(如果使用它)deallocate方法,并且需要一些努力来获取现有库:
Smart pointers add an overhead each time that you assign a pointer to a variable. 每次为变量指定指针时,智能指针都会增加开销。 They don't deal with object networks that have pointer cycles in them.
它们不处理在其中具有指针周期的对象网络。 You need to manually break the cycles to allow the objects reachable from them to be collected.
您需要手动中断周期以允许收集从中可以访问的对象。
In spite of this, either of Boehm GC or Smart pointers would be less implementation and maintenance effort than rolling your own solution. 尽管如此,与滚动您自己的解决方案相比,Boehm GC或智能指针中的任何一个都将减少实施和维护工作量。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.