3

My goal is to create simple mark-sweep garbage collector in C++ language. First step in mark phase is to get all roots(thread stacks, global variables ...). So, how can i get or find that roots in my c++ code?

branishko
  • 43
  • 3
  • 1
    You will probably need to write a compiler that collects this information. – Richard Critten Jan 18 '17 at 10:23
  • 1
    Look at the Boehm conservative collector for one possible approach: https://en.wikipedia.org/wiki/Boehm_garbage_collector – Thomas Padron-McCarthy Jan 18 '17 at 11:52
  • One possible thing that you could do is to call a function to register each root object, and let your collector keep a list. Not very convenient, but easy to implement (compared to writing a new compiler), and could still be useful for some cases. Or look at this: http://stackoverflow.com/questions/147130/why-doesnt-c-have-a-garbage-collector?rq=1 – Thomas Padron-McCarthy Jan 18 '17 at 11:54
  • Yes, i saw Boehm collector. I'll give it a try again... Is it possible(i mean easier to implement) collector for C++, but written in C? Edit: Not sure i'm gonna write a new compiler. I'm looking for easiest solution for this part of job, if there is one. – branishko Jan 18 '17 at 12:15
  • a precise collector needs to know the object and stack frame layout. a conservative one can just scan memory regions (stacks, heap) for potential pointers into those regions. – the8472 Jan 18 '17 at 13:44
  • 1
    https://github.com/hsutter/gcpp – Guillaume Racicot Jan 18 '17 at 14:24

1 Answers1

4

There is a talk that Herb Sutter gave at CPPCon 2016 that explains exactly how to correctly make a mark-n-sweep garbage collector in C++: Talk

Martin Rozkin
  • 375
  • 2
  • 6