Why garbage collection when RAII is available?

前端 未结 7 1453
深忆病人
深忆病人 2021-02-01 14:00

I hear talks of C++14 introducing a garbage collector in the C++ standard library itself. What is the rationale behind this feature? Isn\'t this the reason that RAII exists in

7条回答
  •  别跟我提以往
    2021-02-01 14:31

    GC has the following advantages:

    1. It can handle circular references without programmer assistance (with RAII-style, you have to use weak_ptr to break circles). So a RAII style application can still "leak" if it is used improperly.
    2. Creating/destroying tons of shared_ptr's to a given object can be expensive because refcount increment/decrement are atomic operations. In multi-threaded applications the memory locations which contains refcounts will be "hot" places, putting a lot of pressure on the memory subsystem. GC isn't prone to this specific issue, because it uses reachable sets instead of refcounts.

    I am not saying that GC is the best/good choice. I am just saying that it has different characteristics. In some scenarios that might be an advantage.

提交回复
热议问题