Does C++ have a Garbage Collector?

2019-01-19 11:28发布

问题:

I'm currently reading an unreleased master thesis report, that I'm going to give feedback on.

In the report they mention GC under native C++ and managed C++. I thought C++ didn't have any standard GC, am I wrong or right? (They do not mention Boehm-Demers-Weiser.)

They have some problem getting it to work under some conditions. They create objects in one thread, and delete the pointer from another thread.

回答1:

Managed C++ (and its successor C++/CLI) of course use .NET garbage collection for managed resources (though native resources are not garbage collected and have to be managed manually as in native C++).

Native C++ by default has no such thing (the closest thing to this are the smart pointers, but that's still something entirely different), but that doesn't prevent you from writing your own garbage collection solution (or using third party solution).



回答2:

Existing C++ standard of 1998/2004 does not specify a garbage collector. The upcoming standard C++0x does specify an optional garbage collector API, however the implementation is an other part. With all that said, there are garbage collectors available for C++ from compiler vendors and third party.

  • GCC suite provides Boehm-GC for garbage collection.
  • Managed C++ was Microsoft's extension to C++ released with .Net 1.0 which extended C++ with garbage collection capabilities.
  • There is also C++/CIL from Microsoft released with .Net 2 which deprecated Managed C++ with more .Net centric features.
  • Sun Provided libgc as garbage collector for C/C++.


回答3:

The only GC library for C and C++ is Hans-Boehm library, but as far as I know it is difficult to set it.



回答4:

I have a different take on GC under C++.

Have a look at MCP (open source license GPLv3) -- GC with C++ should not have to be any worse than GJC / Mono.