Why this function return an (owned) value?

旧时模样 提交于 2019-12-01 22:50:06

问题


the code from: Genie howto repeat a string N times as an string arrayGenie howto repeat a string N times as an 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) a.str

what is the difference between

return a.str

return (owned) a.str

what is the benefit of (owned)


回答1:


return a.str will make a copy of the string using g_strdup, because by default the function result and the StringBuilder will both own a separate copy of the string after the (implicit) assignment.

Since the StringBuilder stored in a will go out of scope and it's copy will thus never be used again this is not desireable / efficient in this case.

Hence the solution is to pass ownership of the string from a.str to the result of the function using the (owned) directive.

BTW: You can easily find this out 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 documented in the ownership section of the Vala tutorial and also the corresponding part of the Genie tutorial.

I would also recommend the Reference Handling article.



来源:https://stackoverflow.com/questions/31386774/why-this-function-return-an-owned-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!