Why does this function return (owned) value?

code from: Genie howto repeats string N times as Genie string array to repeat string N times as string array

def repeatwithsep (e: string, n: int, separator: string): string
    var elen = e.length;
    var slen = separator.length;
    var a = new StringBuilder.sized ((elen * n) + (slen * (n - 1)) + 1);
    for var i = 0 to (n - 1)
        if i != 0
            a.append_len (separator, slen)
        a.append_len (e, elen)
    return (owned) a.str

      

var a is a local variable, when a goes out of scope it will be destroyed. why this function

return (owned by) a.str

What's the difference between

return a.str

return (owned by) a.str

What's the use (owned)

+3


source to share


1 answer


return a.str

will make a copy of the string with g_strdup

, because by default the result of the function and StringBuilder will have a separate copy of the string after the (implicit) assignment.

Since the StringBuilder stored in a

will go out of scope and the copy will thus never be used again, this is not desirable / efficient in this case.

Hence, the solution is to transfer ownership of the string from a.str

to the result of the function using a directive (owned)

.

BTW: You can easily find this by compiling both versions with valac -C

and comparing the generated C code:



-       _tmp21_->str = NULL;
-       result = _tmp22_;
+       _tmp23_ = g_strdup (_tmp22_);
+       result = _tmp23_;

      

(In this comparison, the left side was return (owned) a.str

and the right side was return a.str

)

PS: This is covered in the owner section of the Vala tutorial , as well as the corresponding part of the Genie tutorial .

I would also recommend link to link .

+5


source







All Articles