In C++11\'s language feature list there is:
Minimal support for garbage collection and reachability-based leak detection
(but
The proposal doesn't introduce a garbage collector - it just allows for it in certain situations if the implementation chooses. The standard will just describe these situations as causing undefined behaviour. In doing this, it relaxes the requirements of the implementation, giving the minimal leeway for a garbage collector.
The simple example given in the proposal considers when you take a pointer to a dynamically allocated object, XOR it with another value, thereby hiding the pointer value, and then recover the original pointer value to access the object through it. Before C++11, this would be perfectly fine and it would still be valid to use. However, now such an operation may be (see next paragraph) considered undefined behaviour, which means that an implementation may do garbage collection on the object that was pointed to.
The standard states that an implementation can either have relaxed pointer safety, in which case the behaviour is as it was before, or strict pointer safety, which allows for the introduction of a garbage collector.
An implementation may have relaxed pointer safety, in which case the validity of a pointer value does not depend on whether it is a safely-derived pointer value. Alternatively, an implementation may have strict pointer safety, in which case a pointer value that is not a safely-derived pointer value is an invalid pointer value unless the referenced complete object is of dynamic storage duration and has previously been declared reachable (20.6.4). [...] It is implementation defined whether an implementation has relaxed or strict pointer safety.
A pointer value is a safely-derived pointer value if it points at a dynamically allocated object and hasn't had any funny business happen to it (defined more specifically in §3.7.4.3).
If your implementation has strict pointer safety yet you still want to do said funny business to a pointer without introducing undefined behaviour, you can declare a pointer p
as being reachable like so:
declare_reachable(p);
This function is defined in the <memory>
header, along with related functions such as undeclare_reachable
, declare_no_pointers
, and undeclare_no_pointers
. You can also determine the strictness of your implementation using get_pointer_safety
.
From Bjarne Stroustrup:
Actually, what I said was something like "When (not if) automatic garbage collection becomes part of C++, it will be optional".
http://www.stroustrup.com/slashdot_interview.html
There is a proposal to remove this GC support from standard:
http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2020/p2186r0.html
and there is an C++ GC(Boehm): https://www.hboehm.info/gc/