Garbage Collection in C++ — why?

后端 未结 16 2104
北恋
北恋 2020-11-29 18:32

I keep hearing people complaining that C++ doesn\'t have garbage collection. I also hear that the C++ Standards Committee is looking at adding it to the language. I\'m afrai

16条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-29 19:04

    Garbage collection is really the basis for automatic resource management. And having GC changes the way you tackle problems in a way that is hard to quantify. For example when you are doing manual resource management you need to:

    • Consider when an item can be freed (are all modules/classes finished with it?)
    • Consider who's responsibility it is to free a resource when it is ready to be freed (which class/module should free this item?)

    In the trivial case there is no complexity. E.g. you open a file at the start of a method and close it at the end. Or the caller must free this returned block of memory.

    Things start to get complicated quickly when you have multiple modules that interact with a resource and it is not as clear who needs to clean up. The end result is that the whole approach to tackling a problem includes certain programming and design patterns which are a compromise.

    In languages that have garbage collection you can use a disposable pattern where you can free resources you know you've finished with but if you fail to free them the GC is there to save the day.


    Smart pointers which is actually a perfect example of the compromises I mentioned. Smart pointers can't save you from leaking cyclic data structures unless you have a backup mechanism. To avoid this problem you often compromise and avoid using a cyclic structure even though it may otherwise be the best fit.

提交回复
热议问题