New to Vala here... trying to understand the difference between properties and getters/setters.
public class Person {
public string name {
get {
XPath.NodeSet* nodes = search (node, "/name");
return nodes->item (0)->get_content ();
}
}
public string get_name() {
XPath.NodeSet* nodes = search (node, "/name");
return nodes->item (0)->get_content ();
}
}
The second get_name ()
function works as expected. The property does not. It throws:
Return value transfers ownership but function return type hasn't been declared to transfer ownership
return nodes->item (0)->get_content ();
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
What am I missing here? Is the get_content ()
not returning a string or does the function solution do some conversion magic?
Thanks!
Normally, functions return owned values (caller must free), but property getters return unowned values (caller must not free). So, the memory returned by get_context ()
will be deallocated and a dangling pointer returned. The values properties return need to either be backed by values that are owned elsewhere (e.g., in a field) or change the return type to be owned so Vala will make a copy of the value.