Shall I delete the pointer manually in v8::External?

不想你离开。 提交于 2019-12-30 10:21:11

问题


Local<ObjectTemplate> tpl = ObjectTemplate::New(isolate);
tpl->SetInternalFieldCount(1);
Local<Object> ret = tpl->NewInstance();
TestExternal* ex = new TestExternal();
ret->SetInternalField(0, External::New(isolate, ex));

Shall I delete the ex pointer manually when ret is no longer in use?

Where's the evidence source code shows that I should or shouldn't do that?


回答1:


Yes, C++ requires manual memory management: if you manually create an object with new, then you also have to manually delete it when it is no longer needed. If you don't delete it, then your program will work, but it will leak memory. If you delete it too early (while other objects still have pointers to it), then that's called a "use-after-free" bug, which typically causes crashes and can be exploited.

There is nothing specific to V8 about this. The v8::External cannot automatically delete your objects because it does not know how your application works -- only you know when the objects can safely be deleted, and how they must be deleted (a void* doesn't know about destructors).

V8's Persistent handles can be marked "weak" and invoke a callback when V8's GC is about to free the object they're referring to. However, the documentation in v8.h strongly recommends not to rely on this:

NOTE: There is no guarantee as to when or even if the callback is invoked. The invocation is performed solely on a best effort basis. As always, GC-based finalization should not be relied upon for any critical form of resource management!

So you should keep track of all your objects on the C++ side and have some plan B for freeing them.




回答2:


If you expect v8::External to delete an object of type TestExternal for you, then you should somehow let it know that it is managing an object of TestExternal.

Since this is usually done via class template and v8::External is not declared as a template, my guess is that it probably won't call delete for you and you need to delete the pointer manually.



来源:https://stackoverflow.com/questions/43961188/shall-i-delete-the-pointer-manually-in-v8external

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!