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

前端 未结 2 1303
闹比i
闹比i 2021-01-13 17:06
Local tpl = ObjectTemplate::New(isolate);
tpl->SetInternalFieldCount(1);
Local ret = tpl->NewInstance();
TestExternal* ex =         


        
                      
相关标签:
2条回答
  • 2021-01-13 17:21

    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.

    0 讨论(0)
  • 2021-01-13 17:28

    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.

    0 讨论(0)
提交回复
热议问题