180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
|
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
|
-
-
-
-
+
+
+
+
-
-
-
-
+
+
+
+
+
+
+
+
|
On the flip side, an abstract list implementation may mimic Tcl 8 behavior by
returning an existing internal reference to a `Tcl_Obj` without incrementing its
reference count. In such instances, calling `Tcl_DecrRefCount` on the element
without a corresponding `Tcl_IncrRefCount` would release an internal reference
held by the abstract list implementation and prematurely free the element resulting
in use-after-free bugs.
To handle both types of implementations correctly, the caller should always use
the `Tcl_BounceRefCount` function on the returned element `Tcl_Obj` when
finished with it. This function will free the passed `Tcl_Obj` if, and only if, there are
no existing references to it.
To handle both types of implementations correctly, the caller should increment
the reference count via `Tcl_IncrRefCount` on the `Tcl_Obj` returned by
`Tcl_ListObjIndex` and decrement it using `Tcl_DecrRefCount` when it will
no longer access it.
If the extension needs to maintain compatibility with Tcl 8.6, an alternative
approach is to perform a pair of `Tcl_IncrRefCount` and `Tcl_DecrRefCount` calls
on the element. While this achieves the same effect as the `Tcl_BounceRefCount`
function, it comes at the cost of a slight efficiency trade-off.
Alternatively, if compatibility with Tcl 8.6 is not required, the same effect can
be achieved slightly more efficiently by passing the returned `Tcl_Obj` to
`Tcl_BounceRefCount` when finished with it. This function will free the passed
`Tcl_Obj` if, and only if, there are no existing references to it. **However, care
must be taken in this case that the `Tcl_Obj` is not passed to functions that
should not be passed `Tcl_Obj` values with a zero reference count
(e.g. `Tcl_ObjSetVar2`).** It is therefore recommended to use the `Tcl_IncrRefCount`/`Tcl_DecrRefCount`
idiom instead.
### Prefer Tcl_ListObjIndex to Tcl_ListObjGetElements for large lists
The introduction of abstract list implementations has an additional consequence
related to iteration over lists. In Tcl 8, it was common practice to iterate
over list elements by calling `Tcl_ListObjGetElements` which returned a pointer
to the array of `Tcl_Obj *` elements stored in the internal representation of a
|