memory management - Why this function return an (owned) value? -
the code from: genie howto repeat string n times string arraygenie howto repeat string n times string array
def repeatwithsep (e: string, n: int, separator: string): string var elen = e.length; var slen = separator.length; var = new stringbuilder.sized ((elen * n) + (slen * (n - 1)) + 1); var = 0 (n - 1) if != 0 a.append_len (separator, slen) a.append_len (e, elen) return (owned) a.str var a local variable, when a goes out of scope, destroyed. why function
return (owned) a.str
what difference between
return a.str
return (owned) a.str
what benefit of (owned)
return a.str make copy of string using g_strdup, because default function result , stringbuilder both own separate copy of string after (implicit) assignment.
since stringbuilder stored in a go out of scope , it's copy never used again not desireable / efficient in case.
hence solution pass ownership of string a.str result of function using (owned) directive.
btw: can find out compiling both versions valac -c , comparing generated c code:
- _tmp21_->str = null; - result = _tmp22_; + _tmp23_ = g_strdup (_tmp22_); + result = _tmp23_; (in comparison left side return (owned) a.str , right side return a.str)
ps: documented in ownership section of vala tutorial , corresponding part of genie tutorial.
i recommend reference handling article.
Comments
Post a Comment