将对象设置为外部而不分配内存

Set object as External without allocating memory

我想 return 一个有自己的对象模板的对象,但我不确定如何在不为该对象分配内存的情况下执行此操作。这是因为我不知道how/when删除这段记忆

这是我目前的情况:

auto objectTemplate = MyObject::GetObjectTemplate(isolate);

auto context = isolate->GetCurrentContext();

auto result = new RespectiveObject();
// set values in `result`...
        
auto instance = objectTemplate->NewInstance(context).ToLocalChecked();
instance->SetInternalField(0, v8::External::New(isolate, result)); // allocation needed for here so `v8::External::New` can store the object instance
        
args.GetReturnValue().Set(instance);

我有办法避免分配,还是有办法以某种方式跟踪此分配并在不再需要时将其删除?也许问题是我对 v8::External 本身的使用?

看起来没有办法避免分配内存,但是内存可以通过使用v8::PersistentBase::SetWeak()进行垃圾回收。