c++ - V8 memory management for argument's return value -


i'm confused how v8 manages memory.

issue:

i understand v8 uses handle refer real instances in memory, , handlescope, local handles can managed automatically , easily. can't undetstand why functioncallbackinfo doesn't use handle keep return value:

void mymethod(const functioncallbackinfo<value>& args)  {     isolate* isolate = isolate::getcurrent();     handlescope scope(isolate);      cout<<"totally "<<args.length()<<" arguments"<<endl;      int result = addopeation(args[0]->int32value(), args[1]->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 line of code !!!     delete [] s; } 

here implementation of functioncallbackinfo::getreturnvalue

template<typename t> returnvalue<t> functioncallbackinfo<t>::getreturnvalue() const {     return returnvalue<t>(&implicit_args_[kreturnvalueindex]); } 

and here implementation of returnvalue::set:

template<typename t> template<typename s> void returnvalue<t>::set(const handle<s> handle) {    type_check(t, s);    if (v8_unlikely(handle.isempty())) {       *value_ = getdefaultvalue();    } else {    *value_ = *reinterpret_cast<internal::object**>(*handle); } 

here definition of returnvalue::value_

  ...   v8_inline void setinternal(internal::object* value) { *value_ = value; }   v8_inline internal::object* getdefaultvalue();   v8_inline explicit returnvalue(internal::object** slot);   internal::object** value_; 

question:

back code - function mymethod, since returnvalue::value_ not handle, safe access returnvalue::value_ once handlescope destroyed?

my guess:

if created 2 classes' instances this:

handlescope s0(...); localhandle<functioncallbackinfo> h0 = ...;     ... {     handlescope s1(...);     localhandle<mytype> h1 = ...;     h0.ptr = *h1; // suppose ptr member field defined in functioncallbackinfo } 

s1 destroyed before s0, @ moment, because s0 still alive, h0, , *h1 member field of h0, v8 gc not cleanup memory referenced *h1 or h0.ptr.

is guess reasonable?

v8::handlescope destroy local handles on scope exit. suppose there no way notify handle scope handle result , shouldn't destroyed. v8::escapablehandlescope allows this:

void mymethod(const functioncallbackinfo<value>& args)  {     isolate* isolate = isolate::getcurrent();     escapablehandlescope scope(isolate);      int result = addopeation(args[0]->int32value(), args[1]->int32value());     char s[10];     _itoa_s(result, s, 9, 10);     local<string> result = string::newfromutf8(isolate, s);     args.getreturnvalue().set(scope.escape(result)); } 

please refer bottom of section handles , garbage collection in v8 guide.


Comments