代码 来自: Genie howto重复一个字符串N时间作为字符串数组 精灵如何将字符串重复N次作为字符串数组
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.strvar a 是局部变量,当 a 超出范围时,它将被销毁. 为什么要使用此功能
var a is a local variable, when a goes out of scope, it will be destroyed. why this function
返回(拥有的)a.str
返回a.str
返回(拥有的)a.str
return (owned) a.str
(拥有)的好处是什么
推荐答案return a.str将使用g_strdup复制字符串,因为默认情况下,函数结果和StringBuilder都将拥有字符串的单独副本(隐式)分配之后.
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.
由于存储在a中的StringBuilder将超出范围,因此将不再使用其副本,因此在这种情况下是不希望的/有效的.
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.
因此,解决方案是使用(owned)指令将字符串的所有权从a.str传递给函数的结果.
Hence the solution is to pass ownership of the string from a.str to the result of the function using the (owned) directive.
顺便说一句:通过使用valac -C编译两个版本并比较生成的C代码,您可以轻松地找到答案:
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_;(在此比较中,左侧为return (owned) a.str,右侧为return a.str)
(In this comparison the left side was return (owned) a.str and the right side was return a.str)
PS:此信息记录在Vala教程的所有权部分以及精灵教程的相应部分.
PS: This is documented in the ownership section of the Vala tutorial and also the corresponding part of the Genie tutorial.
我还会推荐参考处理文章.
更多推荐
为什么此函数返回一个(拥有的)值?
发布评论