可以创建 C++ V8 垃圾收集堆上的对象?
我将 V8 引擎嵌入到 C++ 应用程序中。
我希望利用 V8 中内置的垃圾收集器(特别是压缩功能),但希望存储 C++ 对象。
我不介意需要手动调用收集器来处置对象,只要内存可以回收即可。
I have the V8 engine embedded in a C++ application.
I wish to take advantage of the built in garbage collector (in particularly the compacting feature) in V8 but wish to store C++ objects instead.
I don't mind needing to call the collector manually to dispose of the object, as long as the memory can be reclaimed.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
有趣的想法。我没有使用过 V8,但我写过 C++ 垃圾收集器。我认为答案实际上取决于 V8 用于垃圾回收的算法。标记和清除收集器将内存视为完全平坦的,适用于任何程序,但速度非常慢。大多数收集器都会进行更多特定于语言的优化,并使用实际对象大小和编译器提示来加快速度,这不适用于 C++。
我应该提到,只要不使用编译器提示并天真地对待内存,分代收集器也可以工作。
我编写的 GC 使用我自己的智能指针版本,它非常适合我的特定工作负载。
Interesting thought. I have not used V8 but I have written C++ garbage collectors. I think the answer will actually depend on the algorithm V8 uses for garbage collection. A mark-and-sweep collector, which treats memory as completely flat, will work for any program but its terribly slow. Most collectors do more language specific optimizations and use actual object sizes and compiler hints to speed things up, this wont work with C++.
I should mention that generational collectors can also work as long as they don;t use compiler hints and treat memory naively.
The GC i wrote used my own version of smart pointers and it worked very well for my specific workload.
解释如下:http://code.google.com/apis/v8/embed .html#handles
有关更多信息,请搜索 v8 弱句柄。
It's explained here: http://code.google.com/apis/v8/embed.html#handles
For more info search for v8 weak handles.
我猜答案是否定的,因为 V8 不知道 C++ 对象的内部结构。
您需要 GC 才能扫描 C++ 对象。如果您的代码与
您期望 GC 将扫描
rootObject
的代码相同,请检查它是否具有指向a
和b
的链接并标记a
和b
可行,但是rootObject
对于 V8 来说是一个黑匣子,它不知道它拥有对a
和b
。我认为添加扫描 C++ 对象的能力就像从头开始编写 GC 一样困难。
My guess that the answer is no, because V8 doesn't know an internal structure of C++ objects.
You need the GC to be able to scan C++ objects. If you have a code like
you expect that GC will scan
rootObject
, check that it has links toa
andb
and marka
andb
feasible, butrootObject
is a black box for V8 and it doesn't know that it owns references toa
andb
.I think that adding the ability to scan C++ objects is as hard as writing a GC from scratch.
是的,但并非没有一些工作。 V8 提供了
PersistentBase::SetWeak
来使一个弱句柄,它允许您定义一个回调,您可以使用该回调在垃圾收集时删除本机对象。 但是,不幸的是,V8 并不保证回调会被调用。因此,您需要跟踪创建的本机对象,如果它们同时没有调用回调,请在关闭隔离后删除
它们v8::Isolate::Dispose
。Yes, but not without some work. V8 provides
PersistentBase::SetWeak
to make a weak handle, which allows you to define a callback that you could use to delete your native object on garbage collection. However, unfortunately V8 does not guarantee that the callback will be called. So, you need to keep track of the native objects created, and if they haven't had the callback invoked in the meantime,delete
them yourself after shutting down the isolate withv8::Isolate::Dispose
.