In C++11's language feature list there is:
Minimal support for garbage collection and reachability-based leak detection
(but it seems not implemented in either GCC and Clang.)
Why the standard committee introduced this garbage collection C++ langauge feature?
Does C++ really need a GC? Isn't RAII such an excellent pattern (that can be used uniformly for both memory and non-memory resources, like sockets, files, textures...)?
Will a GC break the uniformity of C++ code pattern that uses RAII?
Some people say that a GC can come in handy to break circular dependencies, but isn't it just OK to use smart pointers like weak_ptr
for this purpose?
And what happens in case of exceptions thrown? How will the stack unwind semantics be modified to take a GC into consideration?
And will a C#-like IDisposable
pattern be introduced as well?
Moreover, assuming that a GC is introduced in C++, will the pointer syntax be different? e.g. Will we have some hat-like "pointers" ^
like in C++/CLI or C++/CX extensions? There should be a way to differentiate from ordinary raw pointers vs. "managed" pointers, right?
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.
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:This function is defined in the
<memory>
header, along with related functions such asundeclare_reachable
,declare_no_pointers
, andundeclare_no_pointers
. You can also determine the strictness of your implementation usingget_pointer_safety
.From Bjarne Stroustrup:
http://www.stroustrup.com/slashdot_interview.html