为什么RAII可用时进行垃圾收集? [英] Why garbage collection when RAII is available?

查看:100
本文介绍了为什么RAII可用时进行垃圾收集?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我听到C ++ 14在C ++标准库中引入一个垃圾回收器的演讲。
此功能的基本原理是什么?这不是RAII存在于C ++的原因吗?

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 C++?


  • 标准库垃圾回收器的存在将如何影响RAII语义?

  • 对我(程序员)或编写C ++程序的方式有何影响?

推荐答案

垃圾收集和RAII在不同的上下文中非常有用。 GC的存在不应影响您对RAII的使用。由于RAII是众所周知的,我给两个例子,GC是方便的。

Garbage collection and RAII are useful in different contexts. The presence of GC should not affect your use of RAII. Since RAII is well-known, I give two examples where GC is handy.

垃圾收集是一个非常有助于实现无锁的数据结构。


[...]无锁数据结构中的一个根本问题。 (来自无锁数据结构作者:Andrei Alexandrescu)

[...] it turns out that deterministic memory freeing is quite a fundamental problem in lock-free data structures. (from Lock-Free Data Structures By Andrei Alexandrescu)

基本上,问题是你必须确保你不会释放内存,而线程正在读取它。这就是GC变得方便:它可以查看线程,只有当它是安全的释放。请仔细阅读这篇文章。

Basically the problem is that you have to make sure you are not deallocating the memory while a thread is reading it. That's where GC becomes handy: It can look at the threads and only do the deallocation when it is safe. Please read the article for details.

只是为了清楚这里:这并不意味着全世界 Java;

Just to be clear here: it doesn't mean that the WHOLE WORLD should be garbage collected as in Java; only the relevant data should be garbage collected accurately.

在他的一个演讲中, Bjarne Stroustrup也给了一个好的,有效的例子,GC变得方便。想象一下用C / C ++编写的应用程序,大小为10M的SLOC。应用程序工作相当好(相当无bug),但它泄漏。你既没有资源(人工小时)也没有功能知识来解决这个问题。源代码是一个有点凌乱的遗留代码。你是做什么?我同意,这可能是最容易和最便宜的方式扫描在与地毯下的问题。

In one of his presentations, Bjarne Stroustrup also gave a good, valid example where GC becomes handy. Imagine an application written in C/C++, 10M SLOC in size. The application works reasonably well (fairly bug free) but it leaks. You neither have the resources (man hours) nor the functional knowledge to fix this. The source code is a somewhat messy legacy code. What do you do? I agree that it is perhaps the easiest and cheapest way to sweep the problem under the rug with GC.

sasha.sochka 指出,垃圾回收器将是可选的

我个人关注的是,人们会开始使用GC,就像它在Java中使用的,并且会写入莽撞的代码和垃圾收集一切。 (我有这样的印象: shared_ptr 已经成为默认的go to,即使在 unique_ptr ,堆栈分配会这样做。)

My personal concern is that people would start using GC like it is used in Java and would write sloppy code and garbage collect everything. (I have the impression that shared_ptr has already become the default 'go to' even in cases where unique_ptr or, hell, stack allocation would do it.)

这篇关于为什么RAII可用时进行垃圾收集?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆