From 978a47e2c52cca0999bbc8eb6d35674d4931ed5c Mon Sep 17 00:00:00 2001 From: Petri Lehtinen Date: Thu, 20 May 2010 18:45:06 +0300 Subject: [PATCH] Clarify the documentation on reference stealing Provide an example usage pattern for reference stealing functions. This way the user (hopely) sees more clearly how the reference stealing functions are meant to be used. --- doc/apiref.rst | 28 +++++++++++++++++++++++++--- 1 file changed, 25 insertions(+), 3 deletions(-) diff --git a/doc/apiref.rst b/doc/apiref.rst index a2a0794..0db662d 100644 --- a/doc/apiref.rst +++ b/doc/apiref.rst @@ -154,9 +154,31 @@ Normally, all functions accepting a JSON value as an argument will manage the reference, i.e. increase and decrease the reference count as needed. However, some functions **steal** the reference, i.e. they have the same result as if the user called :cfunc:`json_decref()` on -the argument right after calling the function. These are usually -convenience functions for adding new references to containers and not -to worry about the reference count. +the argument right after calling the function. These functions are +suffixed with ``_new`` or have ``_new_`` somewhere in their name. + +For example, the following code creates a new JSON array and appends +an integer to it:: + + json_t *array, *integer; + + array = json_array(); + integer = json_integer(42); + + json_array_append(array, integer); + json_decref(integer); + +Note how the caller has to release the reference to the integer value +by calling :cfunc:`json_decref()`. By using a reference stealing +function :cfunc:`json_array_append_new()` instead of +:cfunc:`json_array_append()`, the code becomes much simpler:: + + json_t *array = json_array(); + json_array_append_new(array, json_integer(42)); + +In this case, the user doesn't have to explicitly release the +reference to the integer value, as :cfunc:`json_array_append_new()` +steals the reference when appending the value to the array. In the following sections it is clearly documented whether a function will return a new or borrowed reference or steal a reference to its -- 2.1.4