Search code examples
c++react-nativev8

what does this `context_.Reset` do in v8 runtime implemation of react-native js-runtime?


I m a noob in c++ and v8 engine. when I check the source code of the implementation of v8 JSI, I found which I can not understand: Here is the constructor of the v8 runtime: (pls see comments line below)

V8Runtime::V8Runtime(const std::string &timezoneId) {
  if (!s_platform) {
    s_platform = v8::platform::NewDefaultPlatform();
    v8::V8::InitializeICU();
    v8::V8::InitializePlatform(s_platform.get());
    v8::V8::Initialize();
  }

  arrayBufferAllocator_.reset(
      v8::ArrayBuffer::Allocator::NewDefaultAllocator());
  v8::Isolate::CreateParams createParams;
  createParams.array_buffer_allocator = arrayBufferAllocator_.get();
  isolate_ = v8::Isolate::New(createParams);
#if defined(__ANDROID__)
  if (!timezoneId.empty()) {
    isolate_->DateTimeConfigurationChangeNotification(
        v8::Isolate::TimeZoneDetection::kCustom, timezoneId.c_str());
  }
#endif
  isolate_->Enter();
  v8::HandleScope scopedIsolate(isolate_);
  context_.Reset(isolate_, CreateGlobalContext(isolate_)); 
//what does this reset for? why I need to reset the context just after I create the global context of it?
  context_.Get(isolate_)->Enter();
}

Below is the code of CreateGlobalContext:

v8::Local<v8::Context> V8Runtime::CreateGlobalContext(v8::Isolate *isolate) {
  v8::HandleScope scopedIsolate(isolate);
  v8::Local<v8::ObjectTemplate> global = v8::ObjectTemplate::New(isolate_);
  global->Set(
      v8::String::NewFromUtf8(isolate, "_v8runtime", v8::NewStringType::kNormal)
          .ToLocalChecked(),
      v8::FunctionTemplate::New(isolate, V8Runtime::GetRuntimeInfo));
  return v8::Context::New(isolate_, nullptr, global);
}

repo's origin is here, a v8 implementation of react-native js-runtime. Thank you in advance!


Solution

  • context_ is a global handle (v8::Global), its Reset(...) method is how you assign to the pointer it wraps. So it's being "reset" from being uninitialized to storing the newly created global context here.

    This is probably just defensive programming. – Botje

    No, defensive programming has nothing to do with it.

    Just treat it as an assignment. – Botje

    Yes. If context_ was a v8::Local (which would be a problem for other reasons), then you'd just see context_ = CreateGlobalContext(...) here.