title: V8 memory management for argument's return value
body: <p>I'm confused by how V8 manages its memory. </p>
  
  <p><strong>Issue:</strong></p>
  
  <p>I understand basically V8 uses Handle to refer to the real instances in memory, and with HandleScope, all the local handles  can be managed automatically and easily. But I can't undetstand why  FunctionCallbackInfo doesn't use Handle to keep the return value:</p>
  
  <pre><code>void MyMethod(const FunctionCallbackInfo&lt;Value&gt;&amp; args) 
  {
      Isolate* isolate = Isolate::GetCurrent();
      HandleScope scope(isolate);
  
      cout&lt;&lt;"totally "&lt;&lt;args.Length()&lt;&lt;" arguments"&lt;&lt;endl;
  
      int result = AddOpeation(args[0]-&gt;Int32Value(), args[1]-&gt;Int32Value());
      char *s = new char [10];
      ZeroMemory(s, 10);
      _itoa_s(result, s, 9, 10);
      args.GetReturnValue().Set(String::NewFromUtf8(isolate, s)); // I'm confused by this line of code !!!
      delete [] s;
  }
  </code></pre>
  
  <p>Here is the implementation of <strong>FunctionCallbackInfo::GetReturnValue</strong></p>
  
  <pre><code>template&lt;typename T&gt;
  ReturnValue&lt;T&gt; FunctionCallbackInfo&lt;T&gt;::GetReturnValue() const {
      return ReturnValue&lt;T&gt;(&amp;implicit_args_[kReturnValueIndex]);
  }
  </code></pre>
  
  <p>And here is the implementation of <strong>ReturnValue::Set</strong>:</p>
  
  <pre><code>template&lt;typename T&gt;
  template&lt;typename S&gt;
  void ReturnValue&lt;T&gt;::Set(const Handle&lt;S&gt; handle) {
     TYPE_CHECK(T, S);
     if (V8_UNLIKELY(handle.IsEmpty())) {
        *value_ = GetDefaultValue();
     } else {
     *value_ = *reinterpret_cast&lt;internal::Object**&gt;(*handle);
  }
  </code></pre>
  
  <p>Here is the definition of <strong>ReturnValue::value_</strong>：</p>
  
  <pre><code>  ...
    V8_INLINE void SetInternal(internal::Object* value) { *value_ = value; }
    V8_INLINE internal::Object* GetDefaultValue();
    V8_INLINE explicit ReturnValue(internal::Object** slot);
    internal::Object** value_;
  </code></pre>
  
  <p><strong>Question:</strong></p>
  
  <p>Back to my code - the function MyMethod, since <strong>ReturnValue::value_</strong> is not a handle, will it be safe to access ReturnValue::value_ once the HandleScope is destroyed?</p>
  
  <p><strong>My guess:</strong></p>
  
  <p>If I created two classes' instances like this:</p>
  
  <pre><code>HandleScope s0(...);
  LocalHandle&lt;FunctionCallbackInfo&gt; h0 = ...;    
  ...
  {
      HandleScope s1(...);
      LocalHandle&lt;MyType&gt; h1 = ...;
      h0.ptr = *h1; // Suppose ptr is a member field defined in FunctionCallbackInfo
  }
  </code></pre>
  
  <p>S1 will be destroyed before S0, at that moment, because s0 is still alive, so does h0, and *h1 is a member field of h0, so V8 GC will not cleanup the memory referenced by *h1 or h0.ptr. </p>
  
  <p>Is my guess reasonable?</p>