v8的Handle

本文探讨了V8 JavaScript引擎中Handle的概念,包括Handle的分类和实现细节,以及如何进行Handle的转换操作。通过对Handle的理解,有助于更好地掌握V8内存管理和性能优化。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Handle是v8中最为基础的类,v8为了保证数据访问的正确性和垃圾回收,设计了Handle类
涉及的文件:
include/v8.h
src/handles.h
src/handles-inl.h
src/handles.cc
src/global-handles.h
src/global-handles.cc
src/api.h

  • Handle的分类
    v8对外提供的Handle类定义在v8.h中,它是一个模板类,而且有两个派生类Local和Persistent,他们都是在v8 namespace下的,如果作为v8的使用者应该使用这里的Handle。Local Handle的特点是它们由HandleScope类负责管理,而HandleScope类对象一般作为一个栈分配的本地变量使用,也就是说在栈退出的时候,该类对象会被释放,他所管理的对象也会被释放,也就是说Local Handle所代表的对象会被释放,此时再使用Local Handle访问他所代表的对象将会是不安全和未定义的。Persistent则不同,它的生命周期是由用户维护的,在创建之后,直到我们显式的调用Persistent的Dispose函数。
  • Handle的实现
一.internal::Handle的实现分析
1.Handle的声明
v8在handles.h中定义了v8::internal::Handle类,这是一个v8内部使用的类,所有外部使用的Handle最终都会转换为它,其定义如下:
template<typename T>
class Handle {
public:
  INLINE(explicit Handle(T** location)) { location_ = location; }
  INLINE(explicit Handle(T* obj));
  INLINE( Handle(T* obj, Isolate* isolate));

  INLINE( Handle()) : location_(NULL) {}

  // Constructor for handling automatic up casting.
  // Ex. Handle<JSFunction> can be passed when Handle<Object> is expected.
  template <class S> Handle(Handle<S> handle) {
#ifdef DEBUG
    T* a = NULL;
    S* b = NULL;
    a = b;  // Fake assignment to enforce type checks.
    USE(a);
#endif
    location_ = reinterpret_cast<T**>(handle.location_);
  }

  INLINE(T* operator ->() const) { return operator*(); }

  // Check if this handle refers to the exact same object as the other handle.
  INLINE(bool is_identical_to(const Handle<T> other) const);

  // Provides the C++ dereference operator.
  INLINE( T* operator*() const);

  // Returns the address to where the raw pointer is stored.
  INLINE( T** location() const);

  template <class S> static Handle<T> cast(Handle<S> that) {
    T::cast(*that);
    return Handle<T>(reinterpret_cast<T**>(that.location()));
  }

  static Handle<T> null() { return Handle<T>(); }
  bool is_null() const { return location_ == NULL; }

  // Closes the given scope, but lets this handle escape. See
  // implementation in api.h.
  inline Handle<T> EscapeFrom(v8::HandleScope* scope);

private:
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值