gpt4 book ai didi

node.js - 在异步插件中正确使用 HandleScope

转载 作者:IT老高 更新时间:2023-10-28 23:27:42 25 4
gpt4 key购买 nike

我正在编写一个异步 Node 插件,但我一直在努力弄清楚是否需要在调用客户端 JavaScript 回调的“After”函数中使用 HandleScope。我已经看到有和没有新作用域的例子,但从来没有解释过为什么。这是一个例子:

void asyncWorkAfter(uv_work_t* req) {
HandleScope scope; // <-- Do you need a new scope?

const int argc = 1;
Local<Value> foo = String::New("foo");
Local<Value> argv[] = { foo };

// assume I got my callback function out of req
callback->Call(Context::GetCurrent()->Global(), argc, argv);

callback.Dispose();

// if i use a new HandleScope, what happens to argv when we go out of scope?
// Do i need to do something like a scope.Close() to copy argv to the parent scope?
}

调用回调时是否需要/想要一个 HandleScope?
如果您确实使用了新的 HandleScope,那么示例中的 argv 会发生什么情况?

最佳答案

String::New("foo") 将在堆上分配一些东西并返回一个句柄,因此您需要以某种方式释放此句柄引用的内存。如果您将它们附加到 HandleScope,一旦所有引用计数为零,v8 将为您执行此操作。

Local handles are held on a stack and are deleted when the appropriate destructor is called. These handles' lifetime is determined by a handle scope, which is often created at the beginning of a function call. When the handle scope is deleted, the garbage collector is free to deallocate those objects previously referenced by handles in the handle scope, provided they are no longer accessible from JavaScript or other handles.

https://developers.google.com/v8/embed

关于node.js - 在异步插件中正确使用 HandleScope,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16701275/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com