为什么此函数返回一个(拥有的)值?

编程入门 行业动态 更新时间:2024-10-15 02:25:35
本文介绍了为什么此函数返回一个(拥有的)值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

代码 来自: 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.str

var 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.

我还会推荐参考处理文章.

更多推荐

为什么此函数返回一个(拥有的)值?

本文发布于:2023-10-24 21:12:54,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1525022.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:函数

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!