Why does C++11 allow for GC? [closed]

2019-04-10 03:40发布

问题:

C++11 allows its implementations to perform (some) garbage collection utilities. Why would the standard allow this? I was always under the impression that in C++, you don't pay for what you don't use. To me, (implicit) GC feels like it undermines this ideology. In addition, it's not hard to write and use an explicit garbage collection utility in C++ via smart-pointers.

Second, GC will make some otherwise valid programs invalid. Examples include pointer masking and related low-level pointer "hacks".

int * nums = new int[10];
nums += 2;
*nums = 777; // nothing points to the new'ed int[10] at this point
// oh no! nums could have gotten collected!!! (so lets assume it was)
*nums = 666; // crash (or memory corruption (or something else that's bad))

回答1:

The GC is not required to exist by the C++11 standard, but it might be in the future versions.

It is not going to be enforced on you - it will be there only if you request it. It will not collect your normal pointers, it will not collect the current smart pointers. So, it is still the 'don't use - don't pay for it'. It will work only on the pointers you explicitly ask it to, so your example will still work as it does now.

See Sutter’s Mill: Garbage Collection Synopsis, and C++

Reference counting (#1) is often the best and it’s C++’s default form of GC. But there are reasons to also (not instead) want lazy mark-sweep (#2) garbage collection in C++ to deal with things ref counting can’t deal with, including when potential cycles are unavoidable (in some cases some objects may naturally be shared, but then might refer to each other) and lock-free ABA issues.

By "reference counting", Sutter is refering to std::shared_ptr and similar things.