Why this function return an (owned) value?

≯℡__Kan透↙ 提交于 2019-12-01 20:53:19

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.

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