| 84 | |
| 85 | == When to use == |
| 86 | |
| 87 | In the following cases it is recommended to use `GRefPtr<T>`: |
| 88 | |
| 89 | * When holding references as attribute members of instances. Note that this also makes it easier to write accessor methods at the API level, as the refing/unrefing of objects is done automatically: |
| 90 | {{{ |
| 91 | #!cpp |
| 92 | struct FooPrivate { |
| 93 | GRefPtr<GVariant> someData; |
| 94 | }; |
| 95 | |
| 96 | // Public API method |
| 97 | void foo_set_data(Foo* foo, GVariant* data) { |
| 98 | FooPrivate* priv = foo_get_private(foo); |
| 99 | // Takes care of unrefing the previously held object |
| 100 | // and also refing the passed object. |
| 101 | priv->someData = data; |
| 102 | } |
| 103 | }}} |
| 104 | |
| 105 | * When using local references to objects which should be freed/unrefed when the local variable goes out of scope: |
| 106 | {{{ |
| 107 | #!cpp |
| 108 | void doSomethingWithALocalReference() { |
| 109 | GRefPtr<GVariant> temporaryData = g_variant_new("s", "SpamAndEggs"); |
| 110 | // Use “temporaryData” as needed, it will be freed automatically |
| 111 | // when the variable goes out of scope at the end of the function |
| 112 | } |
| 113 | }}} |
| 114 | |
| 115 | In the following cases it is ''not'' recommended to use `GRefPtr<T>`: |
| 116 | |
| 117 | * When creating an initially unowned object —that is, it has a floating reference— which is going to be passed to another function/object that will consume the floating reference. For example: |
| 118 | {{{ |
| 119 | #!cpp |
| 120 | GVariant* createData(int value) { |
| 121 | // This function does not use the new value; the caller |
| 122 | // is responsible of consuming the floating reference. |
| 123 | return g_variant_new("(si)", "int", value); |
| 124 | } |
| 125 | |
| 126 | void someOtherCode() { |
| 127 | // Picks the GVariant created by the above function and |
| 128 | // grabs the floating reference, to make sure intData is |
| 129 | // freed when it goes out of scope. |
| 130 | GRefPtr<GVariant> intData = createData(42); |
| 131 | useIntData(intData); |
| 132 | } |
| 133 | }}} |